python - 如何在循环内部根据键合并字典
问题描述
所以我有一个嵌套字典列表,我想创建一个字典。几天前我遇到了类似的问题,我认为解决方案非常相似,但我似乎无法掌握它。
这是原始列表:
list = [{'user': 'nikos', 'area': 'Africa', 'keywords': 'Kenya$Egypt'},
{'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'},
{'user': 'maria', 'area': 'US & Canada', 'keywords': 'New York'},
{'user': 'maria', 'area': 'Latin America ', 'keywords': 'Brazil'}]
我想这样创建字典:
dictionary = {'user': 'nikos', 'areas': {'Africa': ['Kenya',
'Egypt'],'Europe': ['Brexit']}
1)我设法创建了这些:
{'user': 'nikos', 'areas': {'Africa': ['Kenya', 'Egypt']}}
{'user': 'nikos', 'areas': {'Europe': ['Brexit']}}
但我不能越过这一点并在我的循环中合并到一个字典中(根据我的尝试,我得到了各种错误)
2)我也尝试过这样的字典理解:
dict_1 = {'user': username, 'areas': {new_profile.get('areas') for x in
new_profs}}
这当然是不正确的,但我想知道我是否接近正确的
username = 'nikos'
user = {}
for i in list:
if i['user'] == username:
new_profile = {'user': username, 'areas': {i['area']: i['keywords'].split('$')}}
if new_profile:
new_profs = []
new_profs.append(new_profile)
解决方案
我会这样做:
#!/usr/bin/python3
l = [
{'user': 'nikos', 'area': 'Africa', 'keywords': 'Kenya$Egypt'},
{'user': 'nikos', 'area': 'Europe', 'keywords': 'Brexit'},
{'user': 'maria', 'area': 'US & Canada', 'keywords': 'New York'},
{'user': 'maria', 'area': 'Latin America ', 'keywords': 'Brazil'}
]
# The end result
result = list()
# First extract the names from the dict and put them in
# a set() to remove duplicates.
for name in set([x["user"] for x in l]):
# define the types that hold your results
user_dict = dict()
area_dict = dict()
keyword_list = list()
for item in l:
if item["user"] == name:
# Get the keywords for a given entry in "l"
# and place them in a dictionary with the area keyword from "l"
keyword_list = item["keywords"].split("$")
area_dict[item["area"]] = keyword_list
# Pack it all together in the result list.
user_dict["name"] = name
user_dict["areas"] = area_dict
result.append(user_dict)
这使:
[
{'name': 'maria', 'areas': {'US & Canada': ['New York'], 'Latin America ': ['Brazil']}},
{'name': 'nikos', 'areas': {'Africa': ['Kenya', 'Egypt'], 'Europe': ['Brexit']}}
]
推荐阅读
- javascript - 如何获取句子作为输入并将其用作另一个文本字段的值?
- reactjs - Hook 需要来自另一个 Hook 的数据,但得到 Error: Rendered more hooks than during the previous render
- reactjs - 有没有办法将媒体流对象存储在 redux 中?使用 redux thunk 什么的?
- javascript - Node JS - 使用 Cookie 的路由行为
- javascript - JavaScript 中 {func(){}} 的含义
- r - (R) 错误:美学长度必须为 1 或与数据相同 (6):x 和 y
- javascript - 单个帖子 api 数据未在反应 js 中呈现
- javascript - Three.js - 如何从另一个类访问创建的场景
- c++ - 如何编写通过坐标读取三角形周长的程序?
- c - 为什么链表的函数名前要加*?