Python 字典理解和循环之间的区别
Difference between Python dictionary comprehension and loop
我正在使用 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 是我真正想要的,但我想用字典理解来做。
字典理解的正确写法是什么?
你不能为此使用字典理解,因为字典理解会生成 一个 字典,其中的键和值取自循环。
您将改用列表推导式:
[{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'}]
我正在使用 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 是我真正想要的,但我想用字典理解来做。
字典理解的正确写法是什么?
你不能为此使用字典理解,因为字典理解会生成 一个 字典,其中的键和值取自循环。
您将改用列表推导式:
[{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'}]