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

标签 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'}]

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 - Python字典理解和循环之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29938422/

相关文章:

python - Py2Exe 和 pkg_resources.iter_entry_points()

python - 如何在django models.py中查询相关模型

python - 当我尝试通过 django 发送电子邮件时出现 Gmail SMTPAuthenticationError

c# - 如何修复 Dictionary<char, char> 的编码?

python - 使用列表中多个字典的条件从键中检索项目

python - Pycharm 中的 traitlets.traitlets.TraitError

python - 删除字典中的键/值对不起作用

python - 将列表列表解析为字典到 pandas DataFrame 时忽略错误

python - 通过列表理解将元组列表转换为具有重复键的字典?

python - 返回不包括指定键的字典副本