<p>你在正确的道路上。基本上,一旦您得到<code>new_profs</code>,您就需要单独处理合并。像这样:</p>
<pre class="lang-py prettyprint-override"><code>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']}}]
</code></pre>