Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update dict without adding new keys?

What is a good 1-liner (other than putting this into a function) to achieve this:

# like dict1.update(dict2) but does not add any keys from dict2
# that are not already in dict1
for k in dict1:
    if k in dict2:
        dict1[k]=dict2[k]

I guess that this would work, but uses a "protected" function:

[dict1.__setitem__(k, dict2[k]) for k in dict1 if k in dict2]
like image 578
Dave Avatar asked Feb 18 '13 16:02

Dave


People also ask

How do you update dictionary keys?

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

Can we update keys in dictionary Python?

Python update() method updates the dictionary with the key and value pairs. It inserts key/value if it is not present. It updates key/value if it is already present in the dictionary. It also allows an iterable of key/value pairs to update the dictionary.

Does dict update overwrite?

The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.

How do you add a key to a dictionary Python if not exists?

Add an item only when the key does not exist in dict in Python (setdefault()) In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value.


1 Answers

Using map/zip As two lines for readability:

match_keys = dict1.keys() & dict2.keys()
dict2.update(**dict(zip(match_keys, map(dict2.get, match_keys))))

Or as a one-liner:

dict2.update(**dict(zip(dict1.keys() & dict2.keys(), map(dict2.get, dict1.keys() & dict2.keys()))))

non-destrctively:

new_dict = {**dict2, **dict(zip(dict1.keys() & dict2.keys(), map(dict2.get, dict1.keys() & dict2.keys())))}
like image 150
Ryan Avatar answered Oct 19 '22 17:10

Ryan