the*_*lse 0 python dictionary python-2.7
我有这样的词典列表:
[{'X': '10'},
{'time': '08:34:51', 'load': 28.27, 'memory': 40},
{'time': '08:34:51', 'load': 28.27, 'memory': 40},
{'X': '15'},
{'time': '08:34:51', 'load': 28.27, 'memory': 40},
{'time': '08:34:51', 'load': 28.27, 'memory': 40}]
Run Code Online (Sandbox Code Playgroud)
我需要将'X'-dic连接到其他字典中.我只需要以下词典列表:
[{'X': '10', 'time': '08:34:51', 'load': 28.27, 'memory': 40},
{'X': '10', 'time': '08:34:51', 'load': 28.27, 'memory': 40},
{'X': '15', 'time': '08:34:51', 'load': 28.27, 'memory': 40},
{'X': '15', 'time': '08:34:51', 'load': 28.27, 'memory': 40}]
Run Code Online (Sandbox Code Playgroud)
这样做的简单方法是什么?我必须提一下,{'time': '08:34:51', 'load': 28.27, 'memory': 40}'X' 列表之间可能有未知数量的此类列表.
使用该.update()方法将一个dict合并到另一个:
somedict.update(otherdict)
Run Code Online (Sandbox Code Playgroud)
要对列表执行此操作,请在循环中检测"source"dicts并将其合并到其他循环中:
source = dict()
for mapping in yourlist:
if 'X' in mapping:
source = mapping
else:
mapping.update(source)
Run Code Online (Sandbox Code Playgroud)
请注意,我从源代码的空dict开始,以防X在第一次运行循环时没有遇到带有密钥的dict .
上面的循环将原始源留在列表中.如果您需要删除这些,最好的办法是创建一个包含更新的dicts的新列表:
source = dict()
output = []
for mapping in yourlist:
if 'X' in mapping:
source = mapping
else:
mapping.update(source)
output.append(mapping)
Run Code Online (Sandbox Code Playgroud)