python - 编目词典列表

标签 python dictionary nested catalog

我有一个字典列表:

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"]

最佳答案

递归地:

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'}]}}

关于python - 编目词典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2509260/

相关文章:

python - 在 pandas 中向日期添加 x 个业务月

Python 3 项目初始化/原型(prototype)制作

python - 如何从列表 "Python": 打印字典

pointers - 从结构指针数组创建映射

python - flask-marshmallow 嵌套架构不适用

javascript - 如何在 Google AppEngine 上实现 "real time"消息传递?

python - 字典到数据框

python - 在列表中设置 dict 字段的 pythonic 方式是什么

c++ - header 包含的嵌套深度是否有限制?

javascript - 在 react 中渲染另一个表的行中的表