data_garden data_garden - 25 days ago 8
Python Question

Python - function to increment dictionary values

Starting from two nested

dictionaries
:

p1 = {'user1': {u'Codex': 1.0, u'High And Dry': 1.0, u'Hey': 1.0, u'O': 1.0, u'Videotape': 1.0, u'Pyramid Song': 1.0}}


and

p2 = {'user1': {u'Codex': 1.0, u'High And Dry': 1.0, u'Hey': 1.0, u'O': 1.0, u'Videotape': 1.0, u'Pyramid Song': 1.0,
u'x': 1.0, u'y': 1.0, u'w': 1.0, u'z': 1.0}}


I am fetching both outer
keys


playlist1 = p1['user1'].keys()
playlist2 = p2['user1'].keys()


In order to define an incremental
function
whose purpose is to increment counts for repeated songs, and keep all others unaffected, I wrote:

def incremented_playlist(playlist1, playlist2):

playlist3 = {'user1':{}}

for song in playlist2:
if song in playlist1:
playlist3['user1'][song] = 2.0
else:
playlist3['user1'][song] = 1.0


return playlist3


this prints the desired
output
for the example:

print incremented_playlist(playlist1, playlist2)


i.e

{'user1': {u'Pyramid Song': 2.0, u'Videotape': 2.0, u'High And Dry': 2.0, u'Hey': 2.0, u'O': 2.0, u'Codex': 2.0, u'w': 1.0, u'y': 1.0, u'x': 1.0, u'z': 1.0}}


but how do I build an increment part where now theres only value assignment?

Is there any
built-in
python
class
which does
increment
better?

Answer

Something like this should work if I understood you correctly. You have 2 playlists and want to make sum of the ratings in the different playlists. So if I have given to some song ratings 1 in both playlists the sum will be 2, if I gave only in one of them the sum will be 1. This solution will work also if there are ratings different than 1.

p1 = {'user1': {u'Codex': 1.0, u'High And Dry': 1.0, u'Hey': 1.0, u'O': 1.0, u'Videotape': 1.0, u'Pyramid Song': 1.0}}
p2 = {'user1': {u'Codex': 1.0, u'High And Dry': 1.0, u'Hey': 1.0, u'O': 1.0, u'Videotape': 1.0, u'Pyramid Song': 1.0,
                u'x': 1.0, u'y': 1.0, u'w': 1.0, u'z': 1.0}}

total = dict()
for user, ratings in p1.items():
    this_user_ratings = ratings
    if user in p2:
        ratings2 = p2[user]
        for k, v in ratings2.items():
            this_user_ratings[k] = this_user_ratings.get(k, 0) + v
    total[user] = this_user_ratings
print(total)

Or if you need a solution that will work with arbitrary number of dictionaries (playlists) you may want to use something like this:

all_playlists = [p1, p2]

total = dict()
for playlist in all_playlists:
    for user, ratings in playlist.items():
        total.setdefault(user, dict())
        for k, v in ratings.items():
            total[user][k] = total[user].get(k, 0) + v