<p>我会这样做:</p>
<pre><code>#!/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)
</code></pre>
<p>它给出:</p>
<pre><code>[
{'name': 'maria', 'areas': {'US & Canada': ['New York'], 'Latin America ': ['Brazil']}},
{'name': 'nikos', 'areas': {'Africa': ['Kenya', 'Egypt'], 'Europe': ['Brexit']}}
]
</code></pre>