【发布时间】:2021-07-02 12:54:11
【问题描述】:
我有 2 个共享信息的列表。首先,我想要一组唯一的名称(例如list_person 重复了name 值);为此,我制作了一个新的字典列表。 然后,当list_pets['person_id'] 与list_person['id'] 匹配时,我想将list_pets['pet'] 添加/附加到具有唯一名称值的新字典中正确的list_person['pets']。
为了澄清,这里是我的代码+所需的输出:
我当前的代码:
list_person = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat']}, # you see that name values are repeated
{'id': 678910, 'name': 'Bobby Bobs', 'pets': ['zebra']},
{'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse']},
{'id': 141516, 'name': 'Lisa Bobs', 'pets': ['rabbit']}]
list_pets = [{'id': 'abcd', 'pet': 'shark', 'person_id': 12345}, #Bobby Bobs' pets
{'id': 'efgh', 'pet': 'tiger', 'person_id': 678910}, #Bobby Bobs' pets
{'id': 'ijkl', 'pet': 'elephant', 'person_id': 111213}, #Lisa Bobs' pets
{'id': 'mnopq', 'pet': 'dog', 'person_id': 141516}] #Lisa Bobs' pets
output = []
for person, pet in zip(list_person, list_pets):
t = [temp_dict['name'] for temp_dict in output]
if person['name'] not in t:
output.append(person) # make a new list of dicts with unique name values
for unique_person in output: # if they share ID, add the missing pets.
if person['id'] == pet['person_id']:
unique_person['pets'].append(pet['pet'])
print(output)
期望的输出:
desired_out = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra', 'shark', 'tiger']},
{'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit', 'elephant', 'dog']}]
当前输出:
[{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'shark', 'elephant']}, {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'elephant']}]
我当前的输出没有显示所有正确的宠物。这是为什么;为了更接近解决方案,有人会给我什么建议?
【问题讨论】:
-
你当前的代码输出什么?
-
我用我当前的输出对问题进行了编辑。上面的所有代码都是可重现的。 :) 谢谢
-
输出的 id 应该是名称的第一次出现
-
这似乎是XY Problem。您在应该使用数据框的地方使用了
dicts;您的 ID 不是唯一的。如果你“正确地”设计这个,这是一个简单的数据框merge和一个groupby。是否有一些系统要求会导致设计决策看起来很糟糕? -
@Rajesh C 不一定是这样。重要的是在字典列表中拥有该名称一次,以及与该人相关的所有宠物。换句话说,没有信息丢失。
标签: python list dictionary nested