使用 Comprehension 创建字典列表

Create a List of Dictionaries using Comprehension

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

在尝试创建这个词典列表时,我反复创建了一个大词典,而不是逐项遍历。

我的代码:

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

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

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 问题 - 在什么情况下,单条目词典列表是所需的格式?例如,为什么不使用元组列表?