Python字典理解和循环之间的区别

时间:2015-04-29 08:35:46

标签: python dictionary dictionary-comprehension

我正在使用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'}]
标题2是我真正想要的,但我想使用字典理解来做到这一点。

写字典理解的正确方法是什么?

1 个答案:

答案 0 :(得分:8)

你不能使用dict理解,因为dict理解会产生一个字典,其中的键和值来自循环。

您改为使用列表理解:

[{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'}]