Lina Linutina
Lina Linutina

Reputation: 443

How do I create a dictionary from two lists, one of them being nested?

I have two lists of data, one of them containing labels:

labels = ['timestamp', 'hour', 'day']

Another list is nested value list, looking like this:

 values = [[1543449657, 13, 'Monday'], [1543449690, 0, 'Thursday'], [1543449841, 15, 'Sunday']]

I want to create a dictionary which takes a key from the the labels list and loops through values in the second list, so the output would look like:

{
    "timestamp": [1543449657, 1543449690, 1543449841],
    "hour": [13, 0, 15],
    "day": ['Monday', 'Thursday', 'Sunday']
}

I am posting my code below.

dic = {} 
for key in labels: 
    for sublist in values:
        for value in sublist:
            dic[key] = value
            sublist.remove(value)
            break
print(dic)

It only inserts values from the first row.

{'timestamp': 1543449657, 'hour': 13, 'day': 'Monday'}

What am I doing wrong?

Upvotes: 2

Views: 184

Answers (2)

Patrick Haugh
Patrick Haugh

Reputation: 60944

You can zip the sublists of values together to get the values of your dictionary:

dict(zip(labels, zip(*values)))
# {'timestamp': (1543449657, 1543449690, 1543449841), 'hour': (13, 0, 15), 'day': ('Monday', 'Thursday', 'Sunday')}

If you need them to be lists, you can map list over them

dict(zip(labels, map(list, zip(*values))))
# {'timestamp': [1543449657, 1543449690, 1543449841], 'hour': [13, 0, 15], 'day': ['Monday', 'Thursday', 'Sunday']}

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

You can use a dict comprehension here

>>> {key: [sub[index] for sub in values] for index, key in enumerate(labels)}
{'timestamp': [1543449657, 1543449690, 1543449841],
 'hour': [13, 0, 15],
 'day': ['Monday', 'Thursday', 'Sunday']}

Upvotes: 2

Related Questions