I have created 3 different dictionary in python , however I believe this cannot be merged into 1 dictionary eg NewDict due to a same Key in all 3 eg Name & Company.
NewDict1 = {'Name': 'John,Davies', 'Company': 'Google'}
NewDict2 = {'Name': 'Boris,Barry', 'Company': 'Microsoft'}
NewDict3 = {'Name': 'Humphrey,Smith', 'Company': 'Microsoft'}
I would like to group above in such a way that my output is as below :
Google : John Davies Microsoft : Boris Barry, Humphrey Smith
Any help will be really appreciated .
Use a defaultdict
:
from collections import defaultdict
dicts = [NewDict1, NewDict2, NewDict3]
out = defaultdict(list)
for d in dicts:
out[d['Company']].append(d['Name'])
dict(out)
output: {'Google': ['John,Davies'], 'Microsoft': ['Boris,Barry', 'Humphrey,Smith']}
for k,v in out.items():
print(f'{k}: {", ".join(v)}')
output:
Google: John,Davies
Microsoft: Boris,Barry, Humphrey,Smith
NewDict1 = {'Name': 'John,Davies', 'Company': 'Google'}
NewDict2 = {'Name': 'Boris,Barry', 'Company': 'Microsoft'}
NewDict3 = {'Name': 'Humphrey,Smith', 'Company': 'Microsoft'}
d = {}
l = [NewDict1, NewDict2, NewDict3]
for each in l:
if each['Company'] not in d.keys():
d[each['Company']] = []
if each['Name'] not in d[each['Company']]:
d[each['Company']].append(each['Name'])
Outputs:
d
{'Google': ['John,Davies'], 'Microsoft': ['Boris,Barry', 'Humphrey,Smith']}
For Plain text
output = ''
for k,v in d.items():
v = [x.replace(',',' ') for x in v]
output+=f" {k}:{','.join(v)}"
output = output.strip()
Print(output) and you get:
'Google:John Davies Microsoft:Boris Barry,Humphrey Smith'
Why don't you use a different structure for your source dictionary ? like instead of {'name': 'jack', 'company': 'google'}
, go for
dict1 = {'Google': ['Jack']}
dict2 = {'Microsoft': ['Susan']}
dict3= {'Google': ['Amit']}
#then you can combine all three dict into one:
def combine_dict(dict_1, dict_2):
for key in dict_1:
val = dict_1[key]
if key in dict_2:
dict_2[key].extend(val)
else:
dict_2[key] = val
return dict_2
new_dict = combine_dict(dict1,dict2)
new_dict = combine_dict(new_dict, dict3)
this should do it
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.