添加到字典列表的值列表中



我在这上面花了太长时间,尝试了各种各样的东西,但一直没有得到任何地方或错误的unhashable type: 'list',任何帮助或方向将非常感激。

我有一个python字典列表:

my_dict = [{'name': 'john doe', 'favorite_color': ['red']}, {'name': 'jane doe', 'favorite_color': ['pink']}, {'name': 'john doe', 'favorite_color': ['blue', 'green']}, {'name': 'jane doe', 'favorite_color': ['grey', 'white']}]

我正在尝试合并一个列表,使输出看起来像:

my_dict = [{'name': 'john doe', 'favorite_color': ['red','blue','green']}, {'name': 'jane done'}, 'favorite_color': ['pink', 'grey', 'white']}]

就像…

my_dict = [
{'name': 'john doe', 'favorite_color': ['red']},
{'name': 'jane doe', 'favorite_color': ['pink']},
{'name': 'john doe', 'favorite_color': ['blue', 'green']},
{'name': 'jane doe', 'favorite_color': ['grey', 'white']}
]
new_list = []
for item in my_dict:
current_names = {val['name']: i for i, val in enumerate(new_list)}
name_index = current_names.get(item['name'])
if name_index is not None:
new_list[name_index]['favorite_color'].extend(item['favorite_color'])
else:
new_item = {'name': item['name'], 'favorite_color': item['favorite_color']}
new_list.append(new_item)

输出:

new_list
[{'name': 'john doe', 'favorite_color': ['red', 'blue', 'green']}, {'name': 'jane doe', 'favorite_color': ['pink', 'grey', 'white']}]

您可以遍历列表中的所有字典并构建一个新字典:

my_dict = [{'name': 'john doe', 'favorite_color': ['red']}, {'name': 'jane doe', 'favorite_color': ['pink']}, {'name': 'john doe', 'favorite_color': ['blue', 'green']}, {'name': 'jane doe', 'favorite_color': ['grey', 'white']}]
favorite_colors = {}
for d in my_dict:

if d['name'] not in favorite_colors:
# start a new key-value pair with an empty list for the name
#    if one isn't already in the new dict
favorite_colors[d['name']] = []
# add favorite_color for each name, using d['name'] as the key for the new dict
favorite_colors[d['name']] += d['favorite_color']
print(favorite_colors)
{'john doe': ['red', 'blue', 'green'], 'jane doe': ['pink', 'grey', 'white']}

这可能比保存一个字典列表更容易处理。

如果您最终需要一个字典列表,您可以再次遍历它并创建一个新列表:

favorite_colors = {}
for d in my_dict:
if d['name'] not in favorite_colors:
favorite_colors[d['name']] = []
favorite_colors[d['name']] += d['favorite_color']
list_of_dicts = []
for name, list_of_colors in favorite_colors.items():
# build a new dict for each name, with 'name' and 'favorite_color' keys
#    and put it in list_of_dicts
list_of_dicts.append({'name': name, 'favorite_color': list_of_colors})
print(list_of_dicts)
[{'name': 'john doe', 'favorite_color': ['red', 'blue', 'green']}, {'name': 'jane doe', 'favorite_color': ['pink', 'grey', 'white']}]

通过两个不同的for循环迭代可能不是最有效的编码,但在这种情况下,我希望它可以帮助了解发生了什么。

相关内容

  • 没有找到相关文章

最新更新