Reputation:
I have two dictionaries which is there within a list. The list looks like this [{'10.1.1.0':[1], '10.1.1.1':[2]}, {'10.1.1.0':[3], '10.1.1.1':[4]}]. What I need is for the same keys i.e. the matching ips I want the corresponding number or value.
Is this possible? Any help would be really appricaiated.
Upvotes: 2
Views: 282
Reputation: 1859
What you are trying to do is not possible with a dictionary in Python. Duplicate keys are not allowed. Instead you could have the same key mapped to multiple values in a list:
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]}
Upvotes: 4