0

this code takes an artist name, album name, and the number of tracks(optional) to build a dictionary representing information about that album. I wanted to build multiple dictionaries using makealbum() in one loop, something like this:

def makealbum(artist, album, tracks=''):
    album = {'Artist' : artist, 'Album title': album}
    return albums
for i in range(3):
    if input("Want to include the number of tracks? (y/n): ") == 'y':
        album+str(i) = makealbum(input("Artist name: "), input("Album name: "), tracks=input("Number of tracks: ")))

my intention was to make album0, album1, and so on but obviously that doesn't work. How can I make multiple dictionaries using makealbum() in this case?

Obviosuly, this would work:

def makealbum(artist, album, tracks=''):
    album = {'Artist' : artist, 'Album title': album}
    return albums
for i in range(3):
    if input("Want to include the number of tracks? (y/n): ") == 'y':
        album1 = makealbum(input("Artist name: "), input("Album name: "), tracks=input("Number of tracks: "))

        album2 = makealbum(input("Artist name: "), input("Album name: "), tracks=input("Number of tracks: "))

storing the dictionaries in a list would also work:

def makealbum(artist, album, tracks=''):
    album = {'Artist' : artist, 'Album title': album}
    return album

albums = []


for i in range(3):
    if input("Want to include the number of tracks? (y/n): ") == 'y':
        albums.append(makealbum(input("Artist name: "), input("Album name: "), tracks=input("Number of tr0acks: ")))
    else:
        albums.append(makealbum(input("Artist name: "), input("Album name: ")))
print(albums)

but how can I do what I'm trying to do? Just wondering if what I'm trying to do is possible.

I also thought of using list comprehension like so:

def makealbum(artist, album, tracks=''):
    album = {'Artist' : artist, 'Album title': album}
    return album

albums = []

album = {str(i): makealbum(input("Artist name: ", input("Album name :")) for i in range(3))}

trying to make a nested dictionary, but python does not recognize i. why is this?: album = {str(i): makealbum(input("Artist name: ", input("Album name :")) for i in range(3))} NameError: name 'i' is not defined

  • 1
    Don't dynamically create variables, it is a terrible practice. Just use a `list`. – juanpa.arrivillaga Apr 22 '21 at 19:08
  • "but how can I do what I'm trying to do? Just wondering if what I'm trying to do is possible" it is only possible in the global scope, by manipulating the `gloabls()` dict. BUT DONT DO IT. It isn't possible to dynamically create local variables. – juanpa.arrivillaga Apr 22 '21 at 19:09
  • 1
    Anyway, your dictionary comprehension isn't working because you parentheses are wrong. That's a *completely separate question though* – juanpa.arrivillaga Apr 22 '21 at 19:18
  • 1
    Add another `)` after `input("Album name :")` and remove one after `range(3)` – Barmar Apr 24 '21 at 06:00

0 Answers0