我有两个字典,它们在一个列表中。该列表如下所示 [{'10.1.1.0':[1], '10.1.1.1':[2]}, {'10.1.1.0':[3], '10.1.1.1':[4]}] . 我需要的是相同的键,即匹配的 ips 我想要相应的数字或值。
这可能吗?任何帮助将真正appricaiated。
使用python中的字典是不可能的。不允许使用重复的密钥。相反,您可以将相同的键映射到列表中的多个值:
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) # {'10.1.1.0': [1, 3], '10.1.1.1': [2, 4]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |