Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a python string so it can be used as the same name of a dictionary

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading