data_garden data_garden - 1 month ago 14
Python Question

Python - merge nested dictionaries

I have this data structure:

playlists_user1={'user1':[
{'playlist1':{
'tracks': [
{'name': 'Karma Police','artist': 'Radiohead', 'count': 1.0},
{'name': 'Bitter Sweet Symphony','artist': 'The Verve','count': 2.0}
]
}
},
{'playlist2':{
'tracks': [
{'name': 'We Will Rock You','artist': 'Queen', 'count': 3.0},
{'name': 'Roxanne','artist': 'Police','count': 5.0}
]
}
},
]
}


playlists_user2={'user2':[
{'playlist1':{
'tracks': [
{'name': 'Karma Police','artist': 'Radiohead', 'count': 2.0},
{'name': 'Sonnet','artist': 'The Verve','count': 4.0}
]
}
},
{'playlist2':{
'tracks': [
{'name': 'We Are The Champions','artist': 'Queen', 'count': 4.0},
{'name': 'Bitter Sweet Symphony','artist': 'The Verve','count': 1.0}
]
}
},
]
}


I would like to merge the two nested dictionaries into one single data structure, whose first
item
would be a
playlist key
, like so:

{'playlist1': {'tracks': [{'count': 1.0, 'name': 'Karma Police', 'artist': 'Radiohead'}, {'count': 2.0, 'name': 'Bitter Sweet Symphony', 'artist': 'The Verve'}]}}


I have tried:

prefs1 = playlists_user1['user1'][0]
prefs2 = playlists_user2['user2'][0]
prefs3 = prefs1.update(prefs2)


to no avail.

how do I solve this?

Answer

Since your playlist values are already a list of lists of dictionaries with one key (a bit obfuscated if you ask me):

combined = {}
for playlist in playlists_user1.values()[0]:
     combined.update(playlist)
for playlist in playlists_user2.values()[0]:
     combined.update(playlist)

or if you have many of these, make a list and:

combined = {}
for playlistlist in user_playlists:
    for playlist in playlistlist.values()[0]:
        combined.update(playlist)