[英]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.