Reputation: 349
I have two dicts-
dict1 = {'a':'value','b':'value','d':'value'}
and
dict2 = {'p':'blank','q':'blank','r':'blank','s':'blank'}
. Their keys are stored in two lists- list1 = ['a','b','c','d']
and list2 = ['p','q','r','s']
. dict1
might not always contain all key:value pairs.
I want to add entries from dict1
to dict2
, if keys exist in dict1 else I want "blank"
I wrote this code:
for i in list1:
if i in dict1.keys():
dict2[i] = dict1[i]
else:
dict2[i] = "blank"
This will give me dict2
with keys from list1
. How can I modify this code to preserve the conditionality but keep keys associated with dict2
i.e., ['p','q','r','s']
?
My desired output
dict2 = {'p':1,'q':2,'r':'blank','s':4}
The number of keys will always be the same in the two dicts.
Also, is there a more pythonic way to do this? I saw some answers here but did not understand completely.
Upvotes: 1
Views: 63
Reputation: 6494
If I understand you correctly, you want to update dict2
if the item in list1
is in dict1
using the corresponding key in list2
.
You can zip the lists and iterate over the keys in both lists, setting the value using a conditional statement.
dict1 = {'a':1,'b':2,'d':4}
dict2 = {'p':'blank','q':'blank','r':'blank','s':'blank'}
list1 = ['a','b','c','d']
list2 = ['p','q','r','s']
for a, b in zip(list1, list2):
dict2[b] = dict1[a] if a in dict1 else 'blank'
print(dict2)
Output:
{'p': 1, 'q': 2, 'r': 'blank', 's': 4}
Alternatively you can use the dictionary's update()
method and update all the values in one line:
dict2.update({b : dict1[a] if a in dict1 else 'blank' for a,b in zip(list1, list2)})
update()
takes a dictionary of items. In the line above you are creating a temporary dictionary with a dictionary comprehension and updating dict2
.
Upvotes: 0
Reputation: 7983
So if I understand correctly, you want to "map" the keys of list1
to the keys of list2
? In which case, you can zip
the two lists to iterate over the two lists in order, then keep the rest of the code same. One small improvement is that i in dict1.keys()
is actually the same as i in dict1
.
for i, j in zip(list1, list2):
if i in dict1:
dict2[j] = dict1[i]
else:
dict2[j] = "blank"
Upvotes: 1