Reputation: 2388
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.
Upvotes: 1
Views: 37598
Reputation: 4806
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]
Upvotes: 10
Reputation: 7142
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]
Upvotes: 1
Reputation: 10141
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())
Upvotes: 5