将列表中的字典转换为一个字典

时间:2016-05-27 22:15:11

标签: python list dictionary

result = [{u'timestamp': 1464246000, u'value': 36.9},
          {u'timestamp': 1464246900, u'value': 34.61},
          {u'timestamp': 1464247200, u'value': 34.84}]
zzz = {}
for x in result:
    zzz[x['timestamp']] = x['value']
print zzz

{1464246000:36.9,1464247200:34.84,1464246900:34.61}

但是,我需要这样的(dict comprehension):

lst = [{'1': 'A'},{'2': 'B'},{'3': 'C'}]
print {k:v for x in lst for k,v in x.items()}
{'2': 'B', '3': 'C', '1': 'A'}

怎么做?

1 个答案:

答案 0 :(得分:-1)

result = [{u'timestamp': 1464246000, u'value': 36.9},
          {u'timestamp': 1464246900, u'value': 34.61},
          {u'timestamp': 1464247200, u'value': 34.84}]

result是一个词典列表。

从词典列表中创建值词典:

{dictionary['timestamp']:dictionary['value'] for dictionary in result}

输出:

{1464246000: 36.9, 1464247200: 34.84, 1464246900: 34.61}

因此制作价值对{val0_1: val0_2, val1_1:val1_2, ..}