繁体   English   中英

使用 Comprehension 创建字典列表

[英]Create a List of Dictionaries using Comprehension

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

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

我的代码:

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}```

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

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}```

我试图使列表中的每个条目成为与目标 output 图像相同形式的新字典。

clothes_dict = [{clothes_list[i]: clothes_list[i + 1]} for i in range(0, len(clothes_list), 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 问题——在什么情况下,单条目字典列表是所需的格式? 例如,为什么不使用元组列表?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM