我有两本词典,位于列表中。该列表如下所示 [{'10.1.1.0':[1], '10.1.1.1':[2]}, {'10.1.1.0':[3], '10.1.1.1':[4]}] 。我需要的是相同的键,即匹配的 ip,我想要相应的数字或值。
- 因此示例输出如下所示 [{'10.1.1.0':[1], '10.1.1.0':[3]}, {'10.1.1.1':[2], '10.1.1.1':[4] }]
这可能吗?任何帮助将非常感激。
Python 中的字典无法实现您想要做的事情。重复的钥匙不允许 https://realpython.com/python-dicts/#restrictions-on-dictionary-keys。相反,您可以将相同的键映射到列表中的多个值:
x = [{'10.1.1.0': [1], '10.1.1.1': [2]}, {'10.1.1.0': [3], '10.1.1.1': [4]}]
new_dict = dict() # initialize a new dictionary
for d in x: # iterate over the original list of dictionaries
for k, v in d.items(): # get all the items in the current dictionary
if k in new_dict: # add the key and value, or add the value to a key
new_dict[k] += v
else:
new_dict[k] = v
print(new_dict)
Output:
{'10.1.1.0': [1, 3], '10.1.1.1': [2, 4]}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)