简体   繁体   English

从单一列表构建字典的最Pythonic方法

[英]Most Pythonic Way to Build Dictionary From Single List

I have a list of day names (typically Monday-Saturday, though special cases apply) that I want to create a dictionary out of. 我有要创建字典的日期名称列表(通常是星期一至星期六,尽管有特殊情况)。 I want to initialize the value of each day to zero. 我想将每天的值初始化为零。

If I had a list of zeroes the same length of the list of days, this would be a simple use case of zip() . 如果我的零列表与天列表的长度相同,那么这将是zip()的简单用例。 However, a list of zeroes is a waste of space, and if that were the only solution I'd just as soon do something like: 但是,零列表会浪费空间,如果这是唯一的解决方案,我将尽快执行以下操作:

for day in weekList:
    dayDict[day] = 0

Is there a more pythonic way? 还有更Python化的方式吗?

Use the .fromkeys() class method : 使用.fromkeys()类方法

dayDict = dict.fromkeys(weekList, 0)

It builds a dictionary using the elements from the first argument (a sequence) as the keys, and the second argument (which defaults to None ) as the value for all entries. 它使用第一个参数(一个序列)的元素作为键,并使用第二个参数(默认为None )作为所有条目的值来构建字典。

By it's very nature, this method will reuse the value for all keys; 从本质上讲,此方法将对所有键重用该值; don't pass it a mutable value such as a list or dict and expect it to create separate copies of that mutable value for each key. 不要将其传递为可变值,例如列表或字典,并希望它为每个键创建该可变值的单独副本。 In that case, use a dict comprehension instead: 在这种情况下,请改用dict理解:

dayDict = {d: [] for d in weekList}

Apart from dict.fromkeys you can also use dict-comprehension , but fromkeys() is faster than dict comprehensions: 除了dict.fromkeys之外,您还可以使用dict-comprehension ,但是fromkeys()比dict理解要快:

In [27]: lis = ['a', 'b', 'c', 'd']

In [28]: dic = {x: 0 for x in lis}

In [29]: dic
Out[29]: {'a': 0, 'b': 0, 'c': 0, 'd': 0}

For 2.6 and earlier: 对于2.6及更早版本:

In [30]: dic = dict((x, 0) for x in lis)

In [31]: dic
Out[31]: {'a': 0, 'b': 0, 'c': 0, 'd': 0}

timeit comparisons: timeit比较:

In [38]: %timeit dict.fromkeys(xrange(10000), 0)         # winner
1000 loops, best of 3: 1.4 ms per loop

In [39]: %timeit {x: 0 for x in xrange(10000)}
100 loops, best of 3: 2.08 ms per loop

In [40]: %timeit dict((x, 0) for x in xrange(10000))
100 loops, best of 3: 4.63 ms per loop

As mentioned in comments by @Eumiro and @mgilson it is important to note that fromkeys() and dict-comprehensions may return different objects if the values used are mutable objects: 正如@Eumiro和@mgilson在评论中所提到的,必须注意,如果使用的值是可变对象,则fromkeys()dict-comprehensions可能返回不同的对象:

In [42]: dic = dict.fromkeys(lis, [])

In [43]: [id(x) for x in dic.values()]
Out[43]: [165420716, 165420716, 165420716, 165420716] # all point to a same object

In [44]: dic = {x: [] for x in lis}

In [45]: [id(x) for x in dic.values()]
Out[45]: [165420780, 165420940, 163062700, 163948812]  # unique objects

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

相关问题 构建此词典的最pythonic方法是什么? - What's the most pythonic way to build this dictionary? 从中间对列表进行排序的最 Pythonic 方式? - Most Pythonic way to sort a list from middle? 用序列中的列表值创建字典的最简洁(最Pythonic)方法是什么? - What's the cleanest (most Pythonic) way of creating a dictionary with list values from a sequence? 更新相同字典列表中的字典值的最pythonic方法? - Most pythonic way to update a dictionary value in a list of same dictionaries? 基于另一本字典的 bool 创建字典列表的最 Pythonic 方法 - most pythonic way to create list of dictionaries based on bool of another dictionary 什么是将字典中元组的第二个 object 收集到列表中的最pythonic方式 - Whats most pythonic way of colelcting second object of tuple in dictionary into a list 从记录列表中填充字典的 Pythonic 方法 - Pythonic way to populate a dictionary from list of records Pythonic从嵌套字典生成列表的方法 - Pythonic way to produce a list from nested dictionary 是否有更多pythonic方式来构建这个字典? - Is there a more pythonic way to build this dictionary? 将列表中的值用作另一个列表的索引的最pythonic方法 - most pythonic way to use a value from a list as an index to another list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM