I have the list of sets like so. I basically want to convert this to the dictionary and to address duplicate keys, I want to take a text value which is longer in length:
[('hong kong', 'state'),
('hong kong', 'city'),
('hong', 'country'),
('kong', 'city'),
('hong kong', 'country')]
I wanted the below-desired result:
{'state': 'hong kong',
'city': 'hong kong',
'country': 'hong kong'}
I have the function that does this but I am sure that there will be an efficient & pythonic way to do this. So I have tried this:
def create_dict(l):
d=defaultdict(list)
for s in l:
key = s[1]
val = s[0]
if d[key]:
if len(val) > len(d[key]):
d[key] = val
else:
d[key] = val
return d