本文翻译自:Python Dictionary Comprehension

Is it possible to create a dictionary comprehension in Python (for the keys)? 是否可以在Python中(对于键)创建字典理解?

Without list comprehensions, you can use something like this: 如果没有列表理解,则可以使用以下内容:

l = []
for n in range(1, 11):l.append(n)

We can shorten this to a list comprehension: l = [n for n in range(1, 11)] . 我们可以将其简化为列表理解: l = [n for n in range(1, 11)]

However, say I want to set a dictionary's keys to the same value. 但是,说我想将字典的键设置为相同的值。 I can do: 我可以:

d = {}
for n in range(1, 11):d[n] = True # same value for each

I've tried this: 我已经试过了:

d = {}
d[i for i in range(1, 11)] = True

However, I get a SyntaxError on the for . 不过,我得到一个SyntaxErrorfor

In addition (I don't need this part, but just wondering), can you set a dictionary's keys to a bunch of different values, like this: 另外(我不需要这部分,只是想知道),您能否将字典的键设置为一堆不同的值,例如:

d = {}
for n in range(1, 11):d[n] = n

Is this possible with a dictionary comprehension? 字典理解有可能吗?

d = {}
d[i for i in range(1, 11)] = [x for x in range(1, 11)]

This also raises a SyntaxError on the for . 这也会在for上引发SyntaxError


#1楼

参考:https://stackoom.com/question/ys5P/Python字典理解


#2楼

You can use the dict.fromkeys class method ... 您可以使用dict.fromkeys类方法...

>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}

This is the fastest way to create a dictionary where all the keys map to the same value. 这是创建字典的最快方法,其中所有键都映射到相同的值。

But do not use this with mutable objects : 不与可变对象使用 :

d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!

If you don't actually need to initialize all the keys, a defaultdict might be useful as well: 如果您实际上不需要初始化所有键,那么defaultdict也可能有用:

from collections import defaultdict
d = defaultdict(True)

To answer the second part, a dict-comprehension is just what you need: 要回答第二部分,您需要的是dict理解:

{k: k for k in range(10)}

You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__ : 您可能不应该这样做,但是您还可以创建dict的子类,如果您覆盖__missing__则该子类的工作方式类似于defaultdict

>>> class KeyDict(dict):
...    def __missing__(self, key):
...       #self[key] = key  # Maybe add this also?
...       return key
...
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}

#3楼

There are dictionary comprehensions in Python 2.7+ , but they don't work quite the way you're trying. Python 2.7+中有字典理解功能 ,但是它们不能完全按照您尝试的方式工作。 Like a list comprehension, they create a new dictionary; 就像列表理解一样,他们创建了一个字典。 you can't use them to add keys to an existing dictionary. 您不能使用它们将键添加到现有字典中。 Also, you have to specify the keys and values, although of course you can specify a dummy value if you like. 同样,您必须指定键和值,尽管您当然可以根据需要指定一个虚拟值。

>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

If you want to set them all to True: 如果要将它们全部设置为True:

>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}

What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. 您似乎想要的是一种在现有字典上一次设置多个键的方法。 There's no direct shortcut for that. 没有直接的捷径。 You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict) to merge the new values into the old dict. 您可以像已经显示的那样循环,也可以使用字典理解来创建具有新值的新字典,然后执行oldDict.update(newDict)将新值合并到旧字典中。


#4楼

>>> {i:i for i in range(1, 11)}
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}

#5楼

Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length 在元组列表上使用dict(),此解决方案将允许您在每个列表中具有任意值,只要它们的长度相同

i_s = range(1, 11)
x_s = range(1, 11)
# x_s = range(11, 1, -1) # Also works
d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))])

#6楼

you can't hash a list like that. 您不能像这样散列表。 try this instead, it uses tuples 试试这个代替,它使用元组

d[tuple([i for i in range(1,11)])] = True

Python字典理解相关推荐

  1. python用字典统计单词出现次数_python - 如何使用字典理解来计算文档中每个单词的出现次数...

    我有一个用python编写的列表,其中充满了文本.就像每个文档中的固定单词.所以对于每个文档,我都有一个列表,然后在列表中列出所有文档. 所有列表只包含唯一的单词.我的目的是计算完整文档中每个单词的出 ...

  2. python字典setdefault方法后接append()的理解

    目录 1.举例 2.运行结果 3.setdefault方法的官方描述 4.分析 5.总结 1.举例 在编程中,我们有时会见到python字典在setdefault方法后面接.append(),我们来看 ...

  3. python 定义字典键为变量_在python字典中使用变量作为键名

    我今天来是因为我有同样的问题.我必须说,我对这些答案很失望!我同意你的观点,这种冗余应该有一个惯用的解决方案.在这种情况下,JavaScript似乎比Python更明智.所以我想增加两个建议. 首先, ...

  4. python 字典循环_Python字典遍历操作实例小结

    本文实例讲述了Python字典遍历操作.分享给大家供大家参考,具体如下: 1 遍历键值对 可以使用一个 for 循环以及方法 items() 来遍历这个字典的键值对. dict = {'evapora ...

  5. python中可以用中文作为变量-在python字典中使用变量作为键名

    Tyson 我今天来是因为我有同样的问题.我必须说,我对答案很失望!我同意你的看法,这种冗余应该有一个惯用的解决办法.在这种情况下,Javascript似乎比Python更明智.所以我想补充两个建议. ...

  6. python字典get计数_Python内部是如何存储GC引用变量的计数的?

    这段时间一直在想一个问题,为什么Python有了GIL依然还要对变量加锁.Google的过程中查看一些东西,有了新的困惑. 一个说法说Python内部保存了一个用户空间和一个内核空间.用户空间通常就是 ...

  7. 这样合并Python字典,可以让程序的运行效率提高4倍

    摘要:在Python中,合并字典有多种方式,通过内建函数.运算符.自定义函数等,都可以完成合并字典的功能,但这些方式,哪些效率低,哪些效率高呢?本文将对这些合并字典的方式进行逐个深度详解,最后会比较这 ...

  8. pythondict增加-python字典键值对的添加和遍历方法

    添加键值对 首先定义一个空字典 >>> dic={} 直接对字典中不存在的key进行赋值来添加 >>> dic["name"]="zh ...

  9. 【Python】Python字典的高级用法-统计计数

    在很多计算任务中,需要统计不同信息出现的次数,最常见的就是统计某段文字中每个词或者每个字出现的次数,也就是常见的词频统计,这个时候,字典就派上了很大的用场,我们看看通过字典怎么进行统计. 我们用鲁迅先 ...

最新文章

  1. 将十进制数转化成二进制数,计算其中1的个数
  2. 1.17 StringBuffer类详解
  3. C++类的Const数组的初始化
  4. 11.19 rpm:RPM包管理器
  5. 小程序 | 微信小程序二级选择器
  6. 陈小玉:算法学习建议
  7. Hibernate学习之createSQLQuery与createQuery的区别及使用
  8. idea一顿切换分之后编译项目提示找不到其他分支类的解决办法~
  9. android隐藏头标题,关于隐藏Android标题栏总结
  10. An动画基础之元件的图形动画与按钮动画
  11. 顺丰java面试题_顺丰java开发面试分享,顺丰java面试经面试题
  12. ‘\t‘和“\t“的区别及作用
  13. 荣耀畅玩8C生猛来袭夺C位,红米Note5看了只能默默躲角落
  14. 应对当今的医疗器械软件测试开发挑战,如何选择测试软件
  15. jvm 性能调优工具之 jstat 命令详解
  16. 2022出海东南亚:马来西亚电商市场现状及网红营销特点
  17. BUUCTF:[SWPU2019]神奇的二维码
  18. 程序员休闲好去处:深圳东湖公园和深圳仙湖植物园精美图片
  19. Android-Framework-GPS定位原理和修改
  20. 转载:【刘铁猛】SQL速通-《教学大纲》

热门文章

  1. 自己动手实现OpenGL!
  2. Android 使用RxJava--基础篇
  3. 请输入有效值,两个最接近的有效值分别为1和2.
  4. StaticLayout的介绍/使用
  5. python从文件中读取数据_使用Python脚本从文件读取数据代码实例
  6. wampserver环境配置局域网访问
  7. Github 入门1 (下载git , 连接本地库与github仓库)
  8. iOS开发之Masonry框架-源码解析
  9. NOIp2018 Mission Failed Level F
  10. IKE phase 2