Search code examples
pythonlistdictionarymethodskey

How to update a value in python dictionary if the key appears multiple times without importing?


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]}

Solution

  • 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 dictionary, 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]}