我有一个词典列表:
people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"},
{"name": "Dan", "city": "Boston", "age": 20, "sex": "M"},
{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"},
{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}]
我想对它们进行编目,例如我选择这些键:
field = ("sex", "age")
我需要一个能给我的函数catalogue(field, people)
:
{ "M":
{ 20: [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"},
{"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}],
21: [{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}]
},
{ "F":
{ 30: [{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] }
}
len(field)==1
时很简单。我想做这样的事情:
c = catalogue(field, people)
for (sex, sex_value) in c.iteritems():
for (age, age_value) in sex_value.iteritems():
print sex, age, age_value["name"]
答案 0 :(得分:8)
递归:
import itertools, operator
def catalog(fields,people):
cur_field = operator.itemgetter(fields[0])
groups = itertools.groupby(sorted(people, key=cur_field),cur_field)
if len(fields)==1:
return dict((k,list(v)) for k,v in groups)
else:
return dict((k,catalog(fields[1:],v)) for k,v in groups)
试验:
import pprint
pprint.pprint(catalog(('sex','age'), people))
{'F': {30: [{'age': 30, 'city': 'Dallas', 'name': 'Dana', 'sex': 'F'}]},
'M': {20: [{'age': 20, 'city': 'NY', 'name': 'Roger', 'sex': 'M'},
{'age': 20, 'city': 'Boston', 'name': 'Dan', 'sex': 'M'}],
21: [{'age': 21, 'city': 'Boston', 'name': 'Roger', 'sex': 'M'}]}}
答案 1 :(得分:0)
import pprint
people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"},
{"name": "Dan", "city": "Boston", "age": 20, "sex": "M"},
{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"},
{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}]
fields = ("sex", "age")
result = {}
for person in people:
tempdict = result
for field in fields[:-1]:
if person[field] in tempdict:
tempdict = tempdict[person[field]]
else:
t = tempdict
tempdict = {}
t[person[field]] = tempdict
key = person[fields[-1]]
if key in tempdict:
tempdict[key].append(person)
else:
tempdict[key] = [person]
pprint.pprint(result)
似乎在做这个工作
答案 2 :(得分:0)
不是最佳的(例如,可以使用defaultdict
进行改进,但我的机器上安装了Python2.4),但是完成了工作:
def catalogue(dicts, criteria):
if not criteria:
return dicts
criterion, rest = criteria[0], criteria[1:]
cat = {}
for d in dicts:
reducedDict = dict(d)
del reducedDict[criterion]
if d[criterion] in cat:
cat[d[criterion]].append(reducedDict)
else:
cat[d[criterion]] = [reducedDict]
retDict = {}
for key, val in cat.items():
retDict[key] = catalogue(val, rest)
return retDict
print catalogue(people, ("sex", "age"))