简体   繁体   中英

How do you create a dictionary from nested lists in Python?

I was hoping that there might be someway to use a comprehension to do this, but say I have data that looks like this:

data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]

My ultimate goal is to create a dictionary where the first nested list holds the keys and the remaining lists hold the values:

{'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

I have tried something like this that gets me close, but as you can tell I am having trouble appending the list in the dictionary values and this code is just overwriting:

d = {data[0][c]: [] + [col] for r, row in enumerate(data) for c, col in enumerate(row)}
>>> d
{'c': [6], 'a': [4], 'b': [5]}

You can use zip in a dict comprehension:

{z[0]: list(z[1:3]) for z in zip(*data)}
Out[16]: {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

How it works:

zip will take the transpose :

list(zip(['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]))
Out[19]: [('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

However, your data is a list of lists, so in order to make sure Python doesn't see a single list but sees three seperate lists, you need zip(*data) instead of zip(data) . There are several posts on the use of * : (1) , (2) , (3) .

list(zip(*data))
Out[13]: [('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

And in the dict comprehension you are taking the first elements as the keys and the remaining two as the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM