[英]Group a List of Python Dictionaries
我有一些來自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 Values
• All City 2 Dictionary Values, etc
Business
• All City 1 Dictionary Values
• All City 2 Dictionary Values, etc
我不知道如何對此進行進一步的研究,因為我不知道正確的'googleable'術語來描述我想要做的事情。
如果您的數據按名稱排序:
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()])
你再次取消名稱,或者你想使用原始的dicts並且你不介意改變它們:
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}]}]
這一切都取決於你是否想再次使用原始的dicts和/或你是否希望將名字保存在dicts中。 您可以組合邏輯的各個部分以獲得您喜歡的任何格式。
這應該工作:
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
語句。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.