【问题标题】:Create a List of Dictionaries using Comprehension使用 Comprehension 创建字典列表
【发布时间】:2022-01-05 10:00:37
【问题描述】:

我目前有一个字符串列表,我正在尝试将每个字符串项创建到字典对象中并将其存储在列表中。

在尝试创建这个字典列表时,我反复创建一个大字典,而不是逐项迭代。

我的代码:

clothes_dict = [{clothes_list[i]: clothes_list[i + 1] for i in range(0, len(clothes_list), 2)}]

错误(所有项目被合并到一个字典中):

clothes_dict = {list: 1} [{'name': 'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
 0 = {dict: 2} {'name': 'Tom', 'age': 10}, {dict: 2} {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}```

目标输出(所有项目被创建到单个列表中的单独字典中):

clothes_dict = {list: 3} [{'name': 'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
 0 = {dict: 2} {'name': 'Tom', 'age': 10}
 1 = {dict: 2} {'name': 'Mark', 'age': 5}
 2 = {dict: 2} {'name': 'Pam', 'age': 7}```

我正在尝试使列表中的每个条目成为与目标输出图像格式相同的新字典。

【问题讨论】:

  • IDE 的图像在这里没有用处。如果您想增加获得有用帮助的几率,以下是您所需要的:Minimal, Reproducible Example
  • PLEASE DO NOT POST TEXT AS IMAGES。将文本复制并粘贴到您的问题中,并使用代码格式化工具正确格式化。图像不可搜索,也无法通过屏幕阅读器为有视力障碍的人解读。使用edit 链接修改您的问题。

标签: python python-3.x list dictionary list-comprehension


【解决方案1】:
clothes_dict = [{clothes_list[i]: clothes_list[i + 1]} for i in range(0, len(clothes_list), 2)]

您在列表推导中错放右大括号“}”并将其放在末尾,这意味着您执行的是字典推导,而不是列表推导,每个项目都是字典。

【讨论】:

    【解决方案2】:

    您的代码创建一个包含单个字典的列表:

    clothes_dict = [{clothes_list[i]: clothes_list[i + 1] for i in range(0,l en(clothes_list), 2)}]
    

    如果您(出于某种原因)想要一个包含单个条目的字典列表:

    clothes_dict = [{clothes_list[i]: clothes_list[i + 1]} for i in range(0,l en(clothes_list), 2)]
    

    但是,在我看来,这可能是一个 XY 问题——在什么情况下,单条目字典列表是必需的格式?例如,为什么不使用元组列表?

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多