'Merge list of dictionaries by key, check for values - add if new, update if different
I'm trying to get rid of duplicated dictionaries with the same keys (by merging them), but also need to keep track of the values they contain. I have 2 lists:
person_list_1 = [
{"name": "John",
"cars": [
{"make": "Audi", "model_year": 2001},
{"make": "BMW", "model_year": 2009}
]
},
{"name": "Mary",
"cars": [
{"make": "Mazda", "model_year": 2003}
]
},
]
person_list_2 = [
{"name": "John",
"cars": [
{"make": "Audi", "model_year": 2017},
{"make": "Volkswagen", "model_year": 2008}
]
},
{"name": "Ben",
"cars": [
{"make": "Ford", "model_year": 1984}
]
}
]
As you can see, two of them have the same name key, but the values are kind of different.
I would like it to look like this eventually:
updated_person_list = [
{"name": "John",
"cars": [
{"make": "Audi", "model_year": 2017},
{"make": "BMW", "model_year": 2009},
{"make": "Volkswagen", "model_year": 2008},
]
},
{"name": "Mary",
"cars": [
{"make": "Mazda", "model_year": 2003},
]
},
{"name": "Ben",
"cars": [
{"make": "Ford", "model_year": 1984}
]
},
]
I.e., find matching dictionary keys between both lists and account for them accordingly - if such a car already exists in the "cars" list but with a different production year, update the nested dictionary.
Tried out many different solutions including collections.defaultdict, itertools.chain, etc, but none of those attempts was successful.
Can anyone please help with this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
