【问题标题】:convert dict in list to one dict [closed]将列表中的字典转换为一个字典 [关闭]
【发布时间】:2016-05-27 22:15:10
【问题描述】:
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}

但是,我需要这样的东西(字典理解):

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'}

如何做到这一点?

【问题讨论】:

标签: python list dictionary


【解决方案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, ..}

【讨论】:

  • 为什么投反对票?
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 2016-09-14
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多