blah
blah

Reputation: 664

Pop a dictionary when one of the values are identical (python)

I have a list of dictionaries, where each dictionary value is different except for the value of 'name':

   list_dicts = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat']},
                 {'id': 678910, 'name': 'Bobby Bobs', 'pets': ['zebra']},
                 {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse']},
                 {'id': 141516, 'name': 'Lisa Bobs', 'pets': ['rabbit']}] 

I would like to delete the second dictionary when the name is the same, but also add the additional pets values to the first dictionary.

desired output:

  output_list_dicts = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']},
                       {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]

I am mainly struggling to identify the items with the same values. I assume after finding those, the items can be 'appended' to the 'pets' nested list and the other dictionaries eliminated using 'pop'.

Upvotes: 0

Views: 34

Answers (3)

Vishal Singh
Vishal Singh

Reputation: 6234

you can use itertools.groupby for this.

import itertools

list_dicts = sorted(list_dicts, key=lambda x: x["name"])
output_list_dicts = []
for key, group in itertools.groupby(list_dicts, key=lambda x: x["name"]):
    group = list(group)
    for g in group[1:]:
        group[0]["pets"].extend(g["pets"])
    output_list_dicts.append(group[0])

print(output_list_dicts)

Output:

[{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']}, {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195553

You can use dict.setdefault for the task:

list_dicts = [
    {"id": 12345, "name": "Bobby Bobs", "pets": ["cat"]},
    {"id": 678910, "name": "Bobby Bobs", "pets": ["zebra"]},
    {"id": 111213, "name": "Lisa Bobs", "pets": ["horse"]},
    {"id": 141516, "name": "Lisa Bobs", "pets": ["rabbit"]},
]

output = {}
for d in list_dicts:
    output.setdefault(
        d["name"], {"id": d["id"], "name": d["name"], "pets": []}
    )["pets"].extend(d["pets"])

output = list(output.values())
print(output)

Prints:

[{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']}, {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]

Upvotes: 1

Peter
Peter

Reputation: 3495

Since name is unique, you ideally want that as your dictionary key, so you can easily test if you've visited it before. Using dict.values() can then get the list output that you're after.

output = {}
for list_dict in list_dicts:
    if list_dict['name'] in output:
        output[list_dict['name']]['pets'].extend(list_dict['pets'])
    else:
        output[list_dict['name']] = list_dict

output_list_dicts = list(output.values())

print(output_list_dicts)
#[{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']},
# {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]

Upvotes: 1

Related Questions