从带有dict的列表中获取键和值

时间:2016-07-21 00:04:26

标签: python list dictionary

我有一个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}
    ]

我想将密钥和值检索到两个列表,例如:

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

以任何方式实现这个目标?

感谢。

3 个答案:

答案 0 :(得分:6)

假设您的词典总是有一个您正在提取的键,值对,您可以使用两个列表推导:

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]

答案 1 :(得分:3)

尝试:

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

对于键和值:

items = dictionary.items()

也可以用来分割它们:

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

答案 2 :(得分:1)

您可以在年度列表中创建两个列表和附加键,并在dividendlist中创建值。

这是代码。

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

输出:

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]

您可以使用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 

输出:

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]