jas*_*onC 1 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))
Run Code Online (Sandbox Code Playgroud)
我认为这两种方法应该给我相同的结果,但我得到以下内容:
titles1 = [{'456': 'ewr', '123': 'asc'}]
titles2 = [{'123': 'asc'}, {'456': 'ewr'}]
Run Code Online (Sandbox Code Playgroud)
titles2是我真正想要的,但我想使用字典理解来做到这一点.
编写字典理解的正确方法是什么?
你不能使用dict理解,因为dict理解产生一个字典,其中的键和值来自循环.
你会使用列表理解:
[{r["section"]: r["title"]} for r in listofdict]
Run Code Online (Sandbox Code Playgroud)
这会在每次迭代时生成一个字典,从而生成一个新列表:
>>> 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'}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |