简体   繁体   English

使用来自列表列表的键/值创建字典

[英]Creating dictionary with key/values coming from a list of lists

Assuming I have a list of lists: 假设我有一个列表列表:

ll = [
         ['a', 'b', 'c'],
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]
     ]

I want to convert it into a dictionary: 我想将其转换为字典:

dl = dict(
    a = [1, 4, 7],
    b = [2, 5, 8],
    c = [3, 6, 9]
)

I currently have following code that does this: 我目前有以下代码执行此操作:

dl = dict((k, 0) for k in ll[0])
for i in range(1, len(ll)):
    for j in range(0, len(ll[0])):
        dl[ll[0][j]].append(ll[i][j])

Is there a simpler/elegant way to do this? 有没有更简单/更优雅的方式来做到这一点?

I am using Python 3, if that matters. 我正在使用Python 3,如果这很重要的话。

Use a dict-comprehension with zip() : 使用zip()的dict-comprehension:

>>> {k: v for k, *v in zip(*ll)}
{'c': [3, 6, 9], 'a': [1, 4, 7], 'b': [2, 5, 8]}

Here zip() with splat operator ( * ) transposes the list items: 这里zip()与splat运算符( * )转置列表项:

>>> list(zip(*ll))
[('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)]

Now we can loop over this iterator return by zip and using the extended iterable packing introduced in Python 3 we can get the key and values very cleanly from each tuple. 现在我们可以通过zip循环遍历此迭代器返回并使用Python 3中引入的扩展可迭代打包 ,我们可以从每个元组中非常干净地获取键和值。

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

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