如何根据键合并字典,在循环内部

2024-06-25 23:26:12 发布

您现在位置: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']}}

但我不能越过那个点,在我的循环中合并成一个dict(根据我的尝试,我得到了各种各样的错误)

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)

Tags: new字典usernameareaprofileeuropekeywordsuser
2条回答

你在正确的道路上。基本上,一旦您得到new_profs,您就需要单独处理合并。像这样:

userlist = [{'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'}]

username = 'nikos'

user = {}
new_profs = []

for i in userlist:
  if i['user'] == username:
    new_profile = {'user': username, 'areas': {i['area']: i['keywords'].split('$')}}
    if new_profile:
        new_profs.append(new_profile)

print new_profs
'''will give you 
[{'user': 'nikos', 'areas': {'Africa': ['Kenya', 'Egypt']}}, {'user': 'nikos', 'areas': {'Europe': ['Brexit']}}]'''

#get all unique users
userset = set([x['user'] for x in new_profs])

merged_profs = []


#for each unique user, go through all the new_profs and merge all of them into one dict
for user in userset:
    merged_dict = {}
    for userprof in new_profs:
        if userprof['user'] == user:
            if merged_dict:
                new_areas = merged_dict.get('areas')
                # you might need to tweak this for your needs. For example, if you want all Europe countries
                # in one dict. Better pull this out into method and add logic accordingly
                new_areas.update(userprof['areas'])
                merged_dict['areas'] = new_areas
            else:
                merged_dict.update(userprof)
    merged_profs.append(merged_dict)

print merged_profs
#gives you [{'user': 'nikos', 'areas': {'Europe': ['Brexit'], 'Africa': ['Kenya', 'Egypt']}}]

我会这样做:

#!/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']}}
]

相关问题 更多 >