对字典列表进行编目
我有一个字典列表:
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"]
I have a list of dictionaries:
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"}]
I want to catalogue them, for example I choose these keys:
field = ("sex", "age")
I need a function catalogue(field, people)
that give me:
{ "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"}] }
}
when len(field)==1
it's simple. I want to do something like this:
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"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
递归地:
测试:
recursively:
test:
似乎可以完成工作
seems do the job
不是最佳的(例如,可以使用
defaultdict
进行改进,但我的机器上安装了 Python2.4),但可以完成工作:Not optimal (could be improved using
defaultdict
, for instance, but I had Python2.4 installed on my machine), but does the job: