user1893110 user1893110 - 1 year ago 69
Python Question

Adding attributes from another dictionary for same key without overwriting

Let's say I have two dictionaries:

d1 = {'a': 2, 'b': 4, 'c': 5, 'd': 6}
d2 = {'a': 5, 'c': 4, 'e': 8}

Iterating over the second:

for k, v in d2.items():

I would like to check for key presence in d1, and if it's there add that value as an attribute to the key and if not, add it to the dictionary so I want:

d1 = {'a': [2, 5], 'b': 4, 'c': [4, 5], 'd': 6, 'e': 8}

I know how to check for presence with the IN operator but can't work out how to update the dict with new attributes.
Bear in mind, I have just presented a simple case of my problem and it will be within a loop which means a key could have multiple attributes rather than just 1 or 2.

Thank you.

Answer Source

You can't have two values for one key in a dictionary. For that, you need the value to be a list to which you append the "real" values for that key.

for k,v in d2.items():
    if k in d1:
        if isinstance(d1[k], list):
            d1[k] = [d1[k], v]

        d1[k] = v

However, this seems more straightforward:

for k,v in d2.items():
    if k in d1:

        d1[k] = [v]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download