Reputation: 57
last_names = ['Bakir','Jose','Jose','Pierce']
university = ['Davis', 'Stanford', 'George Town', 'Berkeley']
resulting_dictionary = {'Bakir':'Davis', 'Jose': ['Stanford', 'George Town'], 'Pierce':'Berkeley'}
dictionary = {key:value for key, value in zip(last_names, university)}
But obtained the following:
{'Bakir': 'Davis', 'Jose': 'George Town', 'Pierce': 'Berkeley'}
Due to duplicate key value in last name list.
Thoughts?
Upvotes: 3
Views: 68
Reputation: 3512
Try this:
my_dict = {}
for key, value in zip(last_names, university):
if key in my_dict:
old_value = my_dict[key]
if isinstance (old_value, str):
my_dict[key] = [old_value, value]
else:
old_value.add (value)
else:
my_dict[key] = value
Upvotes: 0
Reputation: 8695
Assuming, as the question seems to imply, that a list is not desired if only one value is present for a key, a simple flattening post-step can be used to achieve the specified result.
from collections import defaultdict
d = defaultdict(list)
for k, v in zip(last_names, university):
d[k].append(v)
# flatten single entry lists back to a string
d = { k: v[0] if len(v) == 1 else v for k, v in d.items() }
Upvotes: 0
Reputation: 42708
Use defaultdict
from collections import defaultdict
d = defaultdict(list)
for k, v in zip(last_names, university):
d[k].append(v)
Upvotes: 5
Reputation: 106553
You can use the dict.setdefault
method to initialize new keys with sub-lists:
dictionary = {}
for k, v in zip(last_names, university):
dictionary.setdefault(k, []).append(v)
Upvotes: 1
Reputation: 781004
You need to set the value to a list, and check whether the key already exists and append to it.
dictionary = {}
for key, value in zip(last_names, university):
if key in dictionary:
dictionary[key].append(value)
else:
dictionary[key] = [value]
This will make all the values lists. It's generally easier if you're consistent about your data format, not mixing strings and lists. So the result will be:
{'Bakir':['Davis'], 'Jose': ['Stanford', 'George Town']], 'Pierce':['Berkeley']}
Upvotes: 0