Reputation: 29
I have two dictionaries that have the same keys. Both the dictionaries have values which are lists. I want to create a new dictionary which will have list as values and the list elements are based on a condition. The condition is to check if value of 1st list is present in the 2nd list and if it is present then that value should be replaced by 1 and the other elements will be replaced by 0.
For example: Suppose there are two dictionaries as shown below
dict_1={'1': [100], '2':[200],'3':[500]}
dict_2={'1': [100,105,300,600], '2':[100,300,900],'3':[600,300,500]}
Now the resultant dictionary should be like this:
dict_3={'1': [1,0,0,0], '2':[0,0,0],'3':[0,0,1]}
The structure is same as dict_2
with the elements of the list replaced. Since in dict_1
the key '1'
has element 100 in the value list, it will check in dict_2
and if present that element will be replaced by 1 and the rest with 0 in the resulting dict_3
.
How to proceed?
Upvotes: 0
Views: 884
Reputation: 9047
you can use dict comprehension
dict_1={'1': [100], '2':[200],'3':[500]}
dict_2={'1': [100,105,300,600], '2':[100,300,900],'3':[600,300,500]}
dict_3 = {k1: [int(dict_1[k1][0] == i) for i in v1] for k1,v1 in dict_2.items()}
#{'1': [1, 0, 0, 0], '2': [0, 0, 0], '3': [0, 0, 1]}
Upvotes: 1
Reputation: 260390
You can use a dict comprehension:
{k: [int(x in dict_1[k]) for x in v] for k,v in dict_2.items()}
output:
{'1': [1, 0, 0, 0], '2': [0, 0, 0], '3': [0, 0, 1]}
Upvotes: 3
Reputation: 23146
Use dictionary comprehension:
>>> {k: [1 if val in dict_1[k] else 0 for val in v] for k,v in dict_2.items()}
{'1': [1, 0, 0, 0], '2': [0, 0, 0], '3': [0, 0, 1]}
Upvotes: 2