Home > database >  Extracting variable name from file name
Extracting variable name from file name

Time:11-21

I am trying to extract variable names from file names as follows:

happy = "LOL"
angry = "GRRRR"
surprised= "YUPPIE"
file_names=["happy.wav","angry.wav","surprised.wav"

for i in file_names:
  name = i.split('.')
  name_=name[0]
  print(name_)

I get the output as:

happy
angry
surprised

when I wish to get the output as:

"LOL"
"GRRRR"
"YUPPIE"

What is my code missing?

CodePudding user response:

Use a dict, not individual variables, when the variable names should be treated as data.

d = {"happy": "LOL", "angry": "GRRRR", "surprised": "YUPPIE"}
for i in file_names:
    name = i.split(".")[0]
    print(d[name])

CodePudding user response:

I think you are going about this the wrong way. What if the file_names has more file names tomorrow? Would you create more variables? That would be poor design.

What you need is a dictionary. Something like this:

dictionaryOfFileNames = {"happy": "LOL", "angry": "GRRRR", "surprised": "YUPPIE"}
file_names=["happy.wav","angry.wav","surprised.wav"]

for i in file_names:
    name = i.split('.')
    name_=name[0]
    print(dictionaryOfFileNames.get(name_))

In this case, if the name does not exist, you will get a None.

  • Related