简体   繁体   English

从列表创建列表字典

[英]Create a dict of lists from lists

I can create a dict of lists via enumerate() as follows: 我可以通过enumerate()创建列表的字典,如下所示:

def turn_to_dict(*args):
    return {i: v for i, v in enumerate(args)}


lst1 = [1, 2, 3, 4]
lst2 = [3, 4, 6, 7]
lst3 = [5, 8, 9]


x = turn_to_dict(lst1, lst2, lst3)

print(x)

Output: 输出:

{0: [1, 2, 3, 4], 
 1: [3, 4, 6, 7], 
 2: [5, 8, 9]
 }

I want the same thing with one change: I want the keys to be the elements of a list: 我想要做一件事,就是同一件事:我希望键成为列表的元素:

lst1 = ['a', 'b', 'c']
lst2 = [1, 2, 3, 4]
lst3 = [3, 4, 6, 7]
lst4 = [5, 8, 9]


def turn_to_dict(lst, *args):
    for k in lst:
        return {k: v for v in args}


x = turn_to_dict(lst1, lst2, lst3, lst4)

print(x)

I am getting: 我正进入(状态:

{'a': [5, 8, 9]}

What I want is: 我想要的是:

{a: [1, 2, 3, 4], 
 b: [3, 4, 6, 7], 
 c: [5, 8, 9]
 } 

I get no error, just not the output I thought I should be getting. 我没有错误,只是没有得到我认为应该得到的输出。

You need to zip your key-list together with the values: 您需要将键列表和值压缩在一起:

def turn_to_dict(lst, *args):
    return {k: v for k, v in zip(lst, args)}

This pairs up the elements in lst with each of the lists in args . 这将lst的元素与args每个列表配对。

Not that you need to use a dictionary comprehension at all here, dict() accepts an iterable of key-value pairs directly: 此处完全不需要使用字典理解, dict()接受可迭代的键值对:

return dict(zip(lst, args))

You'd only need a dictionary comprehension if either the key or value expressions were more than just a reference to the first and second elements of a 2-value tuple. 如果keyvalue表达式不仅仅是对2值元组的第一个和第二个元素的引用,则仅需要字典理解即可。

Demo: 演示:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3, 4]
>>> lst3 = [3, 4, 6, 7]
>>> lst4 = [5, 8, 9]
>>> args = (lst2, lst3, lst4)
>>> {k: v for k, v in zip(lst1, args)}
{'a': [1, 2, 3, 4], 'b': [3, 4, 6, 7], 'c': [5, 8, 9]}
>>> dict(zip(lst1, args))
{'a': [1, 2, 3, 4], 'b': [3, 4, 6, 7], 'c': [5, 8, 9]}

You don't need all this : 您不需要所有这些:

dict(zip(lst1, [lst2,lst3, lst4]))

using function : 使用功能:

def turn_to_dict(lst, *args):
    return dict(zip(lst, args))

In : 在:

lst1 = ['a', 'b', 'c']
lst2 = [1, 2, 3, 4]
lst3 = [3, 4, 6, 7]
lst4 = [5, 8, 9]

Output : 输出:

>>> turn_to_dict(lst1,lst2,lst3,lst4)
{'a': [1, 2, 3, 4], 'c': [5, 8, 9], 'b': [3, 4, 6, 7]}

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

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