简体   繁体   English

如何使用Python中的嵌套列表创建字典?

[英]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: 您可以在dict理解中使用zip:

{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 : zip将采取转置

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) . 但是,您的数据是列表的列表,因此为了确保Python不会看到一个列表,而是看到三个单独的列表,您需要zip(*data)而不是zip(data) There are several posts on the use of * : (1) , (2) , (3) . 关于*的使用,有几篇文章: (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. 在dict理解中,您将第一个元素作为键,将其余两个作为值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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