I am quite new to python and development in general, so I am sure that my question is phrased a little bit wrong. English is also not my first language, so if you're looking for more info about what I want to do, I will be happy to explain.
Basically, I have a list of dictionaries, where they all share the same keys but different values. For example:
List1 = [{
'name':'yuval',
'age':16,
'favorite_thing_to_do': 'playing the cello' },
{
'name':'yuval',
'age':16,
'favorite_thing_to_do':'hearing music'},
'name':'shiri',
'age':12,
'favorite_thing_to_do':'watch TV'}]
The output I am looking for is a list where favorite_thing_to_do
is merged wherever it can.
For example, the out will be
[{'name':'yuval',
'age':16,
'favorite_thing_to_do': ['playing the cello' , 'hearing music']},
{'name':'shiri',
'age':12,
'favorite_thing_to_do':'watch TV'}]
However, I can't wrap my head about how to do it.
I managed to define a function called merge_dict
, which basically takes two dictionaries, compares the first two keys (name and age) and if the values are the same, it returns a dictionary where favorite_thing_to_do
is a list of the different values in the two different dictionaries that the function received.
As a concept, the function works great; However, I don't know how to run this function over a list with 100+ unfiltered dictionaries; Is there a simpler way to do it?
EDIT: I am going to include the relevant code I have done so far. I have no idea how to do what I want within a list, so I just declared two dictionaries: Item3, Item4 which my function merge_dict concentrated:
Item3 = {
'name':'shiri',
'age':12,
'favorite_thing_to_do':'watch TV'}
Item4 = {
'name':'shiri',
'age':12,
'favorite_thing_to_do': 'listening to teachers'
}
def merge_dict(dict1, dict2):
# we know that dict1 and dict2 are the same length, same keys.
dict3 = {}
for i in dict1:
if dict1[i] == dict2[i]:
dict3[i] = dict1[i]
if i == 'favorite_thing_to_do':
if isinstance(dict1[i], str) and isinstance(dict2[i],str) :
dict3[i] = [dict1[i] , dict2[i]]
if isinstance(dict1[i], list) and isinstance(dict2[i],str):
dict3[i] = dict1[i] + [dict2[i]]
if isinstance(dict1[i], str) and isinstance(dict2[i],list):
dict3[i] = [dict1[i]] + dict1[i]
if isinstance(dict1[i], list) and isinstance(dict2[i],list):
dict3[i] = dict1[i] + dict1[i]
return dict3
print(merge_dict(Item3, Item4))
>>> {'name': 'shiri', 'age': 12, 'favorite_thing_to_do': ['watch TV',
'listening to teachers']}