【问题标题】:Difference between Python dictionary comprehension and loopPython字典理解和循环之间的区别
【发布时间】:2015-04-29 08:35:46
【问题描述】:

我正在使用 Python 3.4,并且正在测试字典理解。

假设我有以下代码:

listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}]
titles1 = []
titles2 = []
titles1.append({r["section"]: r["title"] for r in listofdict})
print("titles1 = " + str(titles1))

for r in listofdict:
  section = r["section"]
  title = r["title"]
  titles2.append({section: title})

print("titles2 = " + str(titles2))

我认为这两种方法应该给我相同的结果,但我得到了以下结果:

titles1 = [{'456': 'ewr', '123': 'asc'}]
titles2 = [{'123': 'asc'}, {'456': 'ewr'}]

titles2 是我真正想要的,但我想使用字典理解来做到这一点。

字典推导式的正确写法是什么?

【问题讨论】:

  • 如果您确切了解(任何类型的)理解如何映射到围绕list.append/set.add/dict[…]=…/yield 的显式循环,那么调试代码会容易得多这:只需将其转换为显式循环,看看它是否是你想要的。 List Comprehensions 上的教程部分实际上解释得很好。

标签: python dictionary dictionary-comprehension


【解决方案1】:

您不能为此使用字典推导,因为字典推导会生成 一个 字典,其中的键和值取自循环。

您应该使用列表推导:

[{r["section"]: r["title"]} for r in listofdict]

这会在每次迭代中生成一个字典,从而生成一个新列表:

>>> listofdict = [{"id":1, "title": "asc", "section": "123"},{"id":2, "title": "ewr", "section": "456"}]
>>> [{r["section"]: r["title"]} for r in listofdict]
[{'123': 'asc'}, {'456': 'ewr'}]

【讨论】:

  • 谢谢!像魅力一样工作!应该意识到我想建立一个字典列表,所以应该使用列表理解。
猜你喜欢
  • 2021-10-31
  • 2020-12-24
  • 1970-01-01
  • 2010-09-06
  • 2011-04-07
  • 2013-10-07
  • 2020-08-10
  • 2011-10-29
相关资源
最近更新 更多