Search code examples
pythonlistdictionaryzip

loop and zip dictionary and list into a new dictionary of lists


How can I double loop over a list and dictionary

provided with this dict:

tabs = {
        'RESULT' : 'result_out',
        'INFO'   : 'info_out',
        'LOGGING'    : 'loggging_out',
        }

And this list:

li = [11,22,33]

I would like to map the dictionary to the list to get this result:

tabs = {
        'RESULT' : [11,'result_out'],
        'INFO'   : [22,'info_out'],
        'LOGGING'    : [33,'loggging_out'],
        }

since:

list(zip(list(tabs.keys()),list(tabs.values()),icons))

is equal to:

[('d', 'a', 1), ('e', 'b', 2), ('f', 'c', 3)]

I thought this would make it:

{key:[icons[i],value] for key,value,i in zip(list(tabs.keys()),list(tabs.values()),icons)}

but this gives:

IndexError: list index out of range

Do you know how can I do this?

Thanks


Solution

  • You can try:

    >>> tabs = {
    ...         'RESULT' : 'result_out',
    ...         'INFO'   : 'info_out',
    ...         'LOGGING'    : 'loggging_out',
    ...         }
    >>> li = [11,22,33]
    >>>
    >>> {a : [c, b] for (a, b), c in zip(tabs.items(), li)}
    {'RESULT': [11, 'result_out'], 'INFO': [22, 'info_out'], 'LOGGING': [33, 'loggging_out']}