Say that I have a list of tuples with multiple occurrences of the same key. I want to convert them into a dictionary but I don't want the keys to repeat or overwrite previous keys. I want to do it without importing packages.
[("John", 14), ("Bob", 5), ("John", 21)]
turn it into:
{"John": [14, 21],
"Bob": [5]}
Try using collections.defaultdict
:
from collections import defaultdict
yourlist = [("John", 14), ("Bob", 5), ("John", 21)]
d = defaultdict(list)
for k, v in yourlist:
d[k].append(v)
print(d)
Output:
defaultdict(<class 'list'>, {'John': [14, 21], 'Bob': [5]})
To make it an actual dict
ionary, add this line:
d = dict(d)
Then:
print(d)
Would give:
{'John': [14, 21], 'Bob': [5]}
Edit:
As OP mentioned in the comments, he doesn't want to use any imports. So try:
yourlist = [("John", 14), ("Bob", 5), ("John", 21)]
d = {}
for x, y in yourlist:
if x in d:
d[x].append(y)
else:
d[x] = [y]
print(d)
Output:
{'John': [14, 21], 'Bob': [5]}