将Python字典列表分组

3
我从API获取了一些JSON数据,它们以字典列表的形式呈现,例如:
entities = [
    {'name': 'McDonalds', 'city': 'New York', 'gross': 250000000, 'id': '000001'},
    {'name': 'McDonalds', 'city': 'Philadelphia', 'gross': 190000000, 'id': '000002'},
    {'name': 'Shake Shack', 'city': 'Los Angeles', 'gross': 17000000, 'id': '000003'},
    {'name': 'In-N-Out Burger', 'city': 'Houston', 'gross': 23000000, 'id': '000004'},
    {'name': 'In-N-Out Burger', 'city': 'Atlanta', 'gross': 12000000, 'id': '000005'},
    {'name': 'In-N-Out Burger', 'city': 'Dallas', 'gross': 950000, 'id': '000006'},
]

我正在尝试将所有具有相同名称的条目分组到另一个字典列表中,该列表以其所属的企业命名。
def group_entities(entities):

    entity_groups = []

    # Establish a blank list for each unique name
    for entity in entities:
        entity['name'] = []
        entity_groups.append(entity['name'])

    # Within each business's list, add separate dictionaries with details
    for entity in entities:
        entity['name'].append({
            'name':entity['name'],
            'city':entity['city'],
            'gross':entity['gross'],
            'id':entity['id']
            })

    entity_groups.extend(entity['name'])

    return entity_groups

我不能使用entity['name']作为变量名,因为它只会更改原始值,也不能使用名称的字符串版本。我想要得到可以迭代和显示数据的结果,例如:
Business
  • All City 1 Dictionary ValuesAll City 2 Dictionary Values, etc
Business
  • All City 1 Dictionary ValuesAll City 2 Dictionary Values, etc

我不知道该如何进行进一步的研究,因为我不知道如何用适当的“谷歌搜索”术语描述我所试图做的事情。

你可以添加输出应该是什么样子的吗? - Padraic Cunningham
3个回答

3
如果你的数据按名称排序:
from itertools import groupby
from operator import itemgetter

entities = [
    {'name': 'McDonalds', 'city': 'New York', 'gross': 250000000, 'id': '000001'},
    {'name': 'McDonalds', 'city': 'Philadelphia', 'gross': 190000000, 'id': '000002'},
    {'name': 'Shake Shack', 'city': 'Los Angeles', 'gross': 17000000, 'id': '000003'},
    {'name': 'In-N-Out Burger', 'city': 'Houston', 'gross': 23000000, 'id': '000004'},
    {'name': 'In-N-Out Burger', 'city': 'Atlanta', 'gross': 12000000, 'id': '000005'},
    {'name': 'In-N-Out Burger', 'city': 'Dallas', 'gross': 950000, 'id': '000006'},
]
data =  [{k: list(v)}  for k, v in groupby(entities, itemgetter("name"))]

这将给你:

[{'McDonalds': [{'id': '000001', 'city': 'New York', 'name': 'McDonalds', 'gross': 250000000}, {'id': '000002', 'city': 'Philadelphia', 'name': 'McDonalds', 'gross': 190000000}]}, {'Shake Shack': [{'id': '000003', 'city': 'Los Angeles', 'name': 'Shake Shack', 'gross': 17000000}]}, {'In-N-Out Burger': [{'id': '000004', 'city': 'Houston', 'name': 'In-N-Out Burger', 'gross': 23000000}, {'id': '000005', 'city': 'Atlanta', 'name': 'In-N-Out Burger', 'gross': 12000000}, {'id': '000006', 'city': 'Dallas', 'name': 'In-N-Out Burger', 'gross': 950000}]}]

或者如果您不想要名称:

 keys = ("id","gross", "city")

 data = [{k: [dict(zip(keys, itemgetter(*keys)(dct))) for dct in v]}  for k, v in groupby(entities, itemgetter("name"))]

如果数据没有排序,您可以使用一个 defaultdict:
from collections import defaultdict

d = defaultdict(list)

for entity in entities:
    d[entity["name"]].append(dict(entity))
print([{k: v} for k,v in d.items()])

再次提醒,您可以删除名称,或者您可能想使用原始字典并且不介意对其进行修改:

from collections import defaultdict

d = defaultdict(list)

for entity in entities:
    d[entity.pop("name")].append(entity)
print([{k: v} for k,v in d.items()])

那将给你带来:
[{'Shake Shack': [{'id': '000003', 'city': 'Los Angeles', 'gross': 17000000}]}, {'McDonalds': [{'id': '000001', 'city': 'New York', 'gross': 250000000}, {'id': '000002', 'city': 'Philadelphia', 'gross': 190000000}]}, {'In-N-Out Burger': [{'id': '000004', 'city': 'Houston', 'gross': 23000000}, {'id': '000005', 'city': 'Atlanta', 'gross': 12000000}, {'id': '000006', 'city': 'Dallas', 'gross': 950000}]}]

这完全取决于您是否想再次使用原始字典,以及是否希望将名称保留在字典中。您可以组合逻辑的部分,以获得您喜欢的任何格式。


1
这应该可以工作:

def group_entities(entities):

    entity_groups = {}

    # Within each business's list, add separate dictionaries with details
    for entity in entities:
        name = entity['name']   # name is the key for entity_groups
        del entity['name']      # remove it from each entity
        # add the entity to the entity_groups with the key (name)
        entity_groups[name] = entity_groups.get(name, []) + [entity]

    return entity_groups

如果您想在每个实体中保留实体名称,则删除del语句。

1
bycompany = {}
for ent in entities:
    if not ent['name'] in bycompany:
        # if there is no location list for this company name,
        # then start a new list for this company.
        bycompany[ent['name']] = []

    # Add the dict to the list of locations for this company.
    bycompany[ent['name']].append(ent)

使用defaultdict将使其成为三行代码:bycompany = defaultdict(list); for ent in entities: bycompany [ent'name'].append(ent) - 9000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接