简体   繁体   English

清单中的Python Append字典

[英]Python Append dictionary in list

[{'Size': 0.0}, {'Size': 19.391637}]
[{'ContainerID': '9bcb46615a',
  'MemUsage': 2.85546875,
  'MaxMem': 1.9522056579589844},
 {'ContainerID': '9aadddf8e0',
  'MemUsage': 17.203125,
  'MaxMem': 1.9522056579589844}]

I have the two lists with dicts above, how can I append the first to the second such that: 我上面有字典,有两个列表,如何将第一个附加到第二个,使得:

[{'ContainerID': '9bcb46615a',
  'MemUsage': 2.85546875,
  'MaxMem': 1.9522056579589844,
  'Size': 0.0},
 {'ContainerID': '9aadddf8e0',
  'MemUsage': 17.203125,
  'MaxMem': 1.9522056579589844,
  'Size': 19.391637}]

If you are using Python3: 如果您使用的是Python3:

s1 = [{'Size': 0.0}, {'Size': 19.391637}]
s2 = [{'ContainerID': '9bcb46615a', 'MemUsage': 2.85546875, 'MaxMem': 1.9522056579589844}, {'ContainerID': '9aadddf8e0', 'MemUsage': 17.203125, 'MaxMem': 1.9522056579589844}]

final_dict = [{**a, **b} for a, b in zip(s2, s1)]

Output: 输出:

[{'MemUsage': 2.85546875, 'ContainerID': '9bcb46615a', 'MaxMem': 1.9522056579589844, 'Size': 0.0}, {'MemUsage': 17.203125, 'ContainerID': '9aadddf8e0', 'MaxMem': 1.9522056579589844, 'Size': 19.391637}]

Explanation: the ** is called dictionary unpacking. 说明: **被称为字典解包。 It splits the contents of the dictionary into its respective key-value pairs and allows you to merge them into one dictionary. 它将字典的内容拆分为各自的键值对,并允许您将它们合并为一个字典。

If you are using Python2: 如果您使用的是Python2:

final_data = [dict(a.items()+b.items()) for a, b in zip(s2, s1)]

Output: 输出:

[{'Size': 0.0, 'MemUsage': 2.85546875, 'ContainerID': '9bcb46615a', 'MaxMem': 1.9522056579589844}, {'Size': 19.391637, 'MemUsage': 17.203125, 'ContainerID': '9aadddf8e0', 'MaxMem': 1.9522056579589844}]

Doing it in-place ( l1 , l2 are your lists): 就地执行此操作( l1l2是您的列表):

for d1, d2 in zip(l1, l2):
    d2.update(d1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM