pythonpython-3.xdictionarypython-3.7python-3.8

How to create a dictionary which will have common keys


I am trying to create a Dictionary using keys and Values

keys = [1,2,3,4,5,1,1,2,2,3,4,4,5,6,7,7,8,9]

and values.

values = ['a', 'b' , 'c' ,'d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

using zip function or using a for loop.

dict1 = dict(zip(keys, values))
print(dict1)

The output is.

{1: 'g', 2: 'i', 3: 'j', 4: 'l', 5: 'm', 6: 'n', 7: 'p', 8: 'q', 9: 'r'}

But the dict ignores the values for common keys. Like it ignores 1: 'a' and many more.

Please tell me a way to deal with it.


Solution

  • Dict cannot have multiple identical keys. But you can have multiple identical values.

    For example:

    a = {
        1: "a",
        1: "b"
    }
    print(a)  # {1: 'b'}
    b = {
        "a": 1,
        "b": 1
    }
    print(b)  # {'a': 1, 'b': 1}
    

    Why

    Keys must be unique, because you access values with my_dict[key]. If my_dict[key] give multiple values, which one do you choose ?

    Alternative

    You can store multiple values for a key in a list:

    keys = [1,2,3,4,5,1,1,2,2,3,4,4,5,6,7,7,8,9]
    values = ['a', 'b' , 'c' ,'d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
    
    dict1 = dict()
    for key, value in zip(keys, values):
        if key in dict1:
            dict1[key].append(value)
        else:
            dict1[key] = [value]
    
    print(dict1)
    # {1: ['a', 'f', 'g'], 2: ['b', 'h', 'i'], 3: ['c', 'j'], 4: ['d', 'k', 'l'], 5: ['e']}
    

    With collections.defaultdict

    from collections import defaultdict
    
    keys = [1,2,3,4,5,1,1,2,2,3,4,4,5,6,7,7,8,9]
    values = ['a', 'b' , 'c' ,'d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
    
    dict1 = defaultdict(list)
    for key, value in zip(keys, values):
        dict1[key].append(value)
    
    print(dict(dict1))
    # {1: ['a', 'f', 'g'], 2: ['b', 'h', 'i'], 3: ['c', 'j'], 4: ['d', 'k', 'l'], 5: ['e']}