【问题标题】:Python create dictionary with defined key and list of values with comprehensionPython创建具有定义键的字典和具有理解的值列表
【发布时间】:2022-01-12 15:50:36
【问题描述】:

如果我有以下 id 列表:

id_numbers = ['08a592a1-5a40-46b7-b9b3-b3a1e6bfdb9f', 'a31017f7-13b4-401c-81ca-fd57042bc181']

我可以使用以下命令将这些 id 编号作为已定义键“id_numbers”的值添加到新字典中:

catalogue_ids = {"id_numbers": []}

for item in id_numbers:
    catalogue_ids["id_numbers"].append(item)

我想知道是否有做同样事情的字典理解方式?

【问题讨论】:

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


    【解决方案1】:
    catalogue_ids = {"id_numbers": [item for item in id_numbers]}
    

    【讨论】:

    • 太好了,非常感谢。
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    无需使用列表/字典推导。您可以简单地将id_numbers 变量分配给字典元素。

    catalogue_ids = {"id_numbers": id_numbers}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-17
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2017-08-14
      相关资源
      最近更新 更多