I have 2 lists that share information. First, I want to have a unique set of names (e.g.list_person
has repeated name
values); For this I produce a new list of dictionaries. Then, I want to add/append list_pets['pet']
to the correct list_person['pets']
in the new dictionary with unique name values, when the list_pets['person_id']
matches the list_person['id']
.
For clarification here is my code + desired output:
My current code:
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 output:
desired_out = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra', 'shark', 'tiger']},
{'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit', 'elephant', 'dog']}]
Current output:
[{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'shark', 'elephant']}, {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'elephant']}]
My current output is not displaying all the correct pets. Why is that; and what advice would one give to me to get closer to the solution?