Home > Back-end >  Convert a python string so it can be used as the same name of a dictionary
Convert a python string so it can be used as the same name of a dictionary

Time:09-11

I have 7 python dictionaries each named after the format songn, for example song1, song2, etc. Each dictionary includes the following information about a song: name, duration, artist. I created a list of songs, called playlist full of the form [song1, song2, song3...,song7].

Here is my code:

song1 = {"name": "Wake Me Up", "duration": 3.5, "artist": "Wham"}
song2 = {"name": "I Want Your...", "duration": 4.3, "artist": "Wham"}
song3 = {"name": "Thriller", "duration": 3.8, "artist": "MJ"}
song4 = {"name": "Monster", "duration": 3.5, "artist": "Rhianna and Eminem"}
song5 = {"name": "Poison", "duration": 5.0, "artist": "Bel Biv Devoe"}
song6 = {"name": "Classic", "duration": 2.5, "artist": "MKTO"}
song7 = {"name": "Edge of Seventeen", "duration": 5.3, "artist": "Stevie Nicks"}

playlist_full = []
for i in range(1, 8):
    song_i = "song" str(i)
    playlist_full.append(song_i)

Now I am trying to use an item in the playlist_full list to in turn get the name of the song in the corresponding dictionary. For example, to see the name of song3, I would like to run:

playlist_full[2].get("name")

The problem is that while playlist[2] is song3, python recognizes it only as a string, and I need python to realize that that string is also the name of a dictionary. What code will allow me to use that string name as the name of the corresponding dictionary?

Edit:

Based on the answer by @rob-g, the following additional lines of code produced the dictionary of songs that I wanted, as well as the method of accessing the name of song3:

playlist_full = [eval(song) for song in playlist]
print(playlist_full[2]["name"]

CodePudding user response:

You could use eval() like:

eval(playlist_full[2]).get("name")

which would do exactly what you want, evaluate the string as python code.

It's not great practice though. It would be better/safer to store the songs themselves in a dictionary or list that can have non-eval'd references.

CodePudding user response:

varnames=locals()
playlist_full = []
for i in range(1, 8):
    song_i = "song" str(i)
    playlist_full.append(varnames[song_i])
    
print(playlist_full[2].get("name"))

CodePudding user response:

You can use locals() built-in function to do that:

for i in range(1, 8):
    song_i = "song" str(i)
    playlist_full.append(locals()[f'song{i}'])
  • Related