大多数Pythonic方式从单一列表构建词典 [英] Most Pythonic Way to Build Dictionary From Single List

查看:118
本文介绍了大多数Pythonic方式从单一列表构建词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想要创建一个字典的日期名称列表(通常是周一至周六,但特殊情况适用)。我想将每一天的价值初始化为零。

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()比dict的理解要快:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆