1

I have a list of dict:

dividends=[ {"2005":0.18}, {"2006":0.21}, {"2007":0.26}, {"2008":0.31}, {"2009":0.34}, {"2010":0.38}, {"2011":0.38}, {"2012":0.38}, {"2013":0.38}, {"2014":0.415}, {"2015":0.427} ] 

I want to retrieve the key and value to two lists, like:

yearslist = [2005,2006, 2007,2008,2009,2010...] dividendlist = [0.18,0.21, 0.26....]

any way to implement this?

thanks.

2
  • Why do you have a list of singleton dictionaries instead of just a dictionary with multiple elements? Commented Jul 21, 2016 at 0:08
  • Other than with iterating the list and dicts? Commented Jul 21, 2016 at 0:08

3 Answers 3

10

Assuming your dictionaries always have a single key,value pair that you are extracting, you could use two list comprehensions:

l1 = [d.values()[0] for d in dividends] # ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'] l2 = [d.keys()[0] for d in dividends] # [0.18, 0.21, 0.26, 0.31, 0.34, 0.38, 0.38, 0.38, 0.38, 0.415, 0.427] 
Sign up to request clarification or add additional context in comments.

Comments

5

Try:

yearslist = dictionary.keys() dividendlist = dictionary.values() 

For both keys and values:

items = dictionary.items() 

Which can be used to split them as well:

yearslist, dividendlist = zip(*dictionary.items()) 

Comments

1

you can create two list and append keys in yearlist and values in dividendlist.

here is the code.

dividends=[ {"2005":0.18}, {"2006":0.21}, {"2007":0.26}, {"2008":0.31}, {"2009":0.34}, {"2010":0.38}, {"2011":0.38}, {"2012":0.38}, {"2013":0.38}, {"2014":0.415}, {"2015":0.427} ] yearlist = [] dividendlist = [] for dividend_dict in dividends: for key, value in dividend_dict.iteritems(): yearlist.append(key) dividendlist.append(value) print 'yearlist = ', yearlist print 'dividendlist = ', dividendlist 

Output:

yearlist = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'] dividendlist = [0.18, 0.21, 0.26, 0.31, 0.34, 0.38, 0.38, 0.38, 0.38, 0.415, 0.427] 

second way you can use list comprehensions

dividends=[ {"2005":0.18}, {"2006":0.21}, {"2007":0.26}, {"2008":0.31}, {"2009":0.34}, {"2010":0.38}, {"2011":0.38}, {"2012":0.38}, {"2013":0.38}, {"2014":0.415}, {"2015":0.427} ] yearlist = [dividend_dict.keys()[0] for dividend_dict in dividends] dividendlist = [dividend_dict.values()[0] for dividend_dict in dividends] print 'yearlist = ', yearlist print 'dividendlist = ', dividendlist 

Output:

yearlist = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'] dividendlist = [0.18, 0.21, 0.26, 0.31, 0.34, 0.38, 0.38, 0.38, 0.38, 0.415, 0.427] 

2 Comments

cool, thanks, that's exactly what I want. do you know any more elegant way?
Thanks , second way you can use list comprehensions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.