Reputation: 29
I have Two dictionaries like below
dic1 = {'1': 'india','2': 'america','3': 'china'}
dic2 = {'A1':'india','A2':'india' ,'A3':'america','A4':'india' ,'A5': 'china','A6': 'india','A7': 'america' }
I want to create new dictionary by comparing the values and store the values in third dictionary as below
dic3 = {'1': [A1,A2,A4,A6], '2': [A3,A7] ,'3': [A5] }
i tried with following code but its not giving expected results
dict3={}
for i in dic1:
for j in dic2:
if i == dic2[j]:
dict3[j]=dic1[i]
print(dict3)
Upvotes: 0
Views: 176
Reputation: 26
If you want your result to be this:
dic3 = {'1': [A1,A2,A4,A6], '2': [A3,A7] ,'3': [A5] }
This will work, I have tried to keep your original solution with some modifications so it will give you desired output:
dic1 = {"1": "india", "2": "america", "3": "china"}
dic2 = {
"A1": "india",
"A2": "india",
"A3": "america",
"A4": "india",
"A5": "china",
"A6": "india",
"A7": "america",
}
dic3 = {}
for i in dic1: # iterate through keys of dic1
lst = [] # list of all the keys of dic2 which have same value as i
for j in dic2: # iterate through keys of dic2
if dic1[i] == dic2[j]: # if value of dic1 is equal to value of dic2
lst.append(j) # add that key to the lst list
dic3[i] = lst # at last after lst is completed add it to dic3 with i as key.
print(dic3)
This is the output:
{'1': ['A1', 'A2', 'A4', 'A6'], '2': ['A3', 'A7'], '3': ['A5']}
Upvotes: 0
Reputation: 29742
One way using collections.defaultdict
:
from collections import defaultdict
tmp = {v: k for k, v in dic1.items()}
dic3 = defaultdict(list)
for k, v in dic2.items():
dic3[tmp[v]].append(k)
dic3 = dict(dic3)
print(dic3)
Output:
{'1': ['A1', 'A2', 'A4', 'A6'], '2': ['A3', 'A7'], '3': ['A5']}
Upvotes: 5
Reputation: 2054
Try out this code:
dic1 = {'1': 'india','2': 'america','3': 'china'}
dic2 = {'A1':'india','A2':'india' ,'A3':'america','A4':'india' ,'A5': 'china','A6': 'india','A7': 'america' }
dic3 = {}
# Iterate through each item pair in dic1
for tup in dic1.items():
# Iterate through each of dic2's keys
for key in dic2.keys():
# Checks if dic2's value equals dic1's value
if dic2[key] == tup[1]:
# If so, either creates a new key or adds to an existing key in dic3
if tup[0] in dic3:
dic3[tup[0]].append(key)
else:
dic3[tup[0]] = [key]
print(dic3)
This iterates through each ITEM PAIR in dic1, checks if dic2's value is equal to dic1's value, and if so appends dic2's key to the value of dic1's key inside of dic3. Complicated stuff.
Upvotes: 1