对字典列表进行编目

发布于 2024-08-26 18:57:34 字数 1027 浏览 7 评论 0原文

我有一个字典列表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

反目相谮 2024-09-02 18:57:34

递归地:

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

recursively:

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)

test:

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'}]}}
指尖上的星空 2024-09-02 18:57:34
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)

似乎可以完成工作

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)

seems do the job

无所谓啦 2024-09-02 18:57:34

不是最佳的(例如,可以使用 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"))

Not optimal (could be improved using defaultdict, for instance, but I had Python2.4 installed on my machine), but does the job:

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"))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文