Search code examples
pythonlistdictionaryzip

Passing a dictionary of lists to the zip function in python


I have a dictionary that groups lists in the form list_hostname and its size can vary depending on the number of hosts.

I would like to zip those lists together along with another list list_timestamp that isn't in the dictionary like so:

zip(list_timestamp, list_hostname1, list_hostname2, ...)

For e.g:

{
  list_hostname1: [1, 6, 7],
  list_hostname2: [4, 2, 8],
  list_hostname3: [3, 5, 0]
}

list_timestamp = ['2019-12-31', '2020-05-21', '2020-06-01']

I want to call the zip function like so:

zip(list_timestamp, list_hostname1, list_hostname2, list_hostname3)

and have this result:

(('2019-12-31', 1, 4, 3), ('2020-05-21', 6, 2, 5), ('2020-06-01', 7, 8, 0))

But the number of lists inside my dictionary can vary so I cannot always assume I am passing 4 arguments to my zip function.

Any idea on how to proceed? Thanks!


Solution

  • You can do this using the values function:

    hostnames = {
      "list_hostname1": [1, 6, 7],
      "list_hostname2": [4, 2, 8],
      "list_hostname3": [3, 5, 0]
    }
    
    list_timestamp = ['2019-12-31', '2020-05-21', '2020-06-01']
    
    for element in zip(list_timestamp, *hostnames.values()):
        print(element)
    

    Which give the output:

    ('2019-12-31', 1, 4, 3)
    ('2020-05-21', 6, 2, 5)
    ('2020-06-01', 7, 8, 0)
    

    Note that dictionaries don't enforce ordering so list_hostname1 might not always be in the second element of the tuple, but I don't know if you need that for your use case.