let's say I have two dictionaries
dict_1 ={'A': 'a', 'B':'b', 'C': 'c', 'D':'d', 'E':'e','F':f}
dict_2 ={'A': None, 'G': None, 'H': None, 'I': None,'L': None}
I'd like a function that returns the second dictionary as
dict_2 ={'A': 'a', 'G': None, 'H': None, 'I': None,'L': None}
which is matching the keys of dict_1 against those in dict_2. If one matches replace the value in dict_2 with the value in dict_1 for that key. Otherwise nothing.
A simple way to do this by iterating over dict_2
's items and using dict_1.get()
providing default value as dict_2
corresponding value -
>>> dict_1 ={'A': 'a', 'B':'b', 'C': 'c', 'D':'d', 'E':'e','F':f}
>>> dict_2 ={'A': None, 'G': None, 'H': None, 'I': None,'L': None}
>>> for k,v in dict_2.items():
... dict_2[k] = dict_1.get(k,v)
...
>>> dict_2
{'G': None, 'H': None, 'I': None, 'L': None, 'A': 'a'}
Same using dict comprehension -
>>> dict_1 ={'A': 'a', 'B':'b', 'C': 'c', 'D':'d', 'E':'e','F':f}
>>> dict_2 ={'A': None, 'G': None, 'H': None, 'I': None,'L': None}
>>> dict_2 = {k:dict_1.get(k,v) for k,v in dict_2.items()}
>>> dict_2
{'G': None, 'H': None, 'I': None, 'L': None, 'A': 'a'}
Another way is to find the common keys, and iterate over them like this:
dict_1 ={'A': 'a', 'B':'b', 'C': 'c', 'D':'d', 'E':'e','F':f}
dict_2 ={'A': None, 'G': None, 'H': None, 'I': None,'L': None}
for key in set(dict_1.iterkeys()) & set(dict_2.iterkeys()):
dict_2[key] = dict_1[key]
This should be much less computational expensive if it's relatively few common entries compared to the total number of entries in the dictionaries.
You could use dict comprehension and if else
to do it :
dict_1 ={'A': 'a', 'B':'b', 'C': 'c', 'D':'d', 'E':'e','F':f}
dict_2 ={'A': None, 'G': None, 'H': None, 'I': None,'L': None}
dict_2={a : dict_1[a] if a in dict_1 else dict_2[a] for a in dict_2.keys() }
print dict_2
output:
{'A': 'a', 'H': None, 'I': None, 'L': None, 'G': None}
But this creates a new dict object
You can use dict.viewkeys
to find the common keys:
dict_1 ={'A': 'a', 'B':'b', 'C': 'c', 'D':'d', 'E':'e','F':'f'}
dict_2 ={'A': None, 'G': None, 'H': None, 'I': None,'L': None}
for k in dict_1.viewkeys() & dict_2.viewkeys():
dict_2[k] = dict_1[k]
print(dict_2)
{'A': 'a', 'H': None, 'I': None, 'L': None, 'G': None}
For python3 just use .keys
as it returns a dictionary-view-object not a list:
for k in dict_1.keys() & dict_2.keys():
dict_2[k] = dict_1[k]
print(dict_2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.