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 ?
ifclause; it just replace any existing value for the key with the new value. So why did you add theifin Python?albis not an album, but a song. See Matthew's or Óscar's answer then."key_1"in place of$key, not gettingsong_namefrom anywhere, and using an explicit loop to copy an array instead of just copying it, which… is silly, and would be just as silly once translated to Python. Can you give us actual working perl code, if you can't give us a clear explanation in English?