[Python] Dict from two lists including multiple values for keys

Discussão em 'Python' iniciado por Stack, Dezembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página