pythondictionary

Dict from two lists including multiple values for keys


Is there a possibility to create a dict from two lists with same key occurring multiple times without iterating over the whole dataset?

Minimal example:

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

# hoped for result:
dictionary = dict(???)
dictionary = {1 : [1,8], 2:[2,4], 3:[3,5], 4:[6], 5:[7]}

When using zip the key-value-pair is inserted overwriting the old one:

dictionary = dict(zip(keys,values))
dictionary = {1: 8, 2: 4, 3: 5, 4: 6, 5: 7}

I would be happy with a Multidict as well.


Solution

  • This is one approach that doesn't require 2 for loops

    h = defaultdict(list)
    for k, v in zip(keys, values):
        h[k].append(v)
    
    print(h)
    # defaultdict(<class 'list'>, {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]})
    
    print(dict(h))
    # {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]}