从单个列表构建字典的最 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.
如果我有一个与天数列表长度相同的零列表,这将是 zip()
的一个简单用例.但是,零列表是一种浪费空间,如果这是唯一的解决方案,我会尽快执行以下操作:
If I had a list of zeroes the same length of the list of days, this would be a simple use case of 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
有没有更pythonic的方式?
Is there a more pythonic way?
推荐答案
除了 dict.fromkeys
你还可以使用 dict-comprehension
,但是 fromkeys()
比字典推导要快:
Apart from dict.fromkeys
you can also use dict-comprehension
,
but fromkeys()
is faster than dict comprehensions:
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}
对于 2.6 及更早版本:
For 2.6 and earlier:
In [30]: dic = dict((x, 0) for x in lis)
In [31]: dic
Out[31]: {'a': 0, 'b': 0, 'c': 0, 'd': 0}
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
正如@Eumiro 和@mgilson 在评论中提到的,重要的是要注意 fromkeys()
和 dict-comprehensions
如果使用的值是可变的,则可能返回不同的对象对象:
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:
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
这篇关于从单个列表构建字典的最 Pythonic 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!