Reputation: 15
I am trying to add keys and value to a python dictionary in a loop. I am quite new to python and I am not able to get it right.
This is my piece of code, where i want to loop through and build the dictionary in a loop with the key being the album name and value being the song list.
for alb in l.songs:
if alb.album not in song_database:
song_database[alb.album] = alb.name
had it been perl i would have done something like this, i am just assuming the kys and values are coming from two different arrays.
foeach(@album_name){
my $key = $_;
foreach(@song_name){
push (@{song_hash{"key"}},$_);
}
}
I would like to know how to do it in python ?
Upvotes: 0
Views: 1973
Reputation: 236084
A shorter and more pythonic solution would be to use a defaultdict:
from collections import defaultdict
song_database = defaultdict(list)
for song in l.songs:
song_database[song.album].append(song.name)
Upvotes: 2
Reputation: 493
If based on your answer to the question above, you want to append if the album is already in the database, try this way:
for alb in l.songs:
if alb.album not in song_database:
song_database[alb.album] = [alb.name]
else:
song_database[alb.album] += [alb.name]
Upvotes: 0
Reputation: 4409
i want to loop through and build the dictionary in a loop with the key being the album name and value being the song list.
It looks like your code is making alb.album
the dictionary key, and alb.name
the dictionary value. Try re-arraging:
for alb in l.songs:
if alb.name not in song_database:
song_database[alb.name] = alb.album
Upvotes: 0
Reputation: 4532
You need to append to an array in python, like you do in perl. Since python does not autovivify you also need to create the array:
for alb in l.songs:
if alb.album not in song_database:
song_database[alb.album] = [alb.name]
else:
song_database[alb.album].append(alb.name)
Upvotes: 4
Reputation: 3782
I think you just forgot to add an indention? Like this:
for alb in l.songs:
if alb.album not in song_database:
song_database[alb.album] = alb.name
Upvotes: 0