1

i am looking for an efficient way to unpack a dictionary's keys and values into variables and values for an arbitrary size and keys. for example:

test = {'key1':'val1','key2':100,'anotherkey':'val3'}

how could i extract variables named key1, key2, and anotherkey with the respective values above in a way that is not sensitive to the number or name of the keys?

i have tried solutions involving map() and .get() but they seem to work when looking for specific keys

laszlopanaflex
  • 1,836
  • 3
  • 23
  • 34
  • You can always use `test['key1']` to get `val1`. I feel that's similar to using a variable. – Austin Jul 10 '19 at 03:00
  • "dynamic variables" is actually a well known antipattern - if you don't know in advance how your variables are named, you just can't use them (remember, this is Python, not PHP - if you try to access a name that is not defined, you get an exception). You may want to read this http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html – bruno desthuilliers Jul 10 '19 at 09:08

1 Answers1

-1

Try this,

test = {'key1':'val1','key2':100,'anotherkey':'val3'}
for key,val in test.items():
    exec(key + '=val')

print(key1)
# val1

print(key2)
# 100

print(anotherkey)
# val3
Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58
  • Any point to down vote this answer as well as the other answers? I just wonder. – Kushan Gunasekera Jul 10 '19 at 09:08
  • @brunodesthuilliers yes you are correct, I also try [Running exec inside function](https://stackoverflow.com/q/2626582/6194097) question solution, it works when we have one value. How can achive this inside the function and rest of the code areas too? Can you provide any guidelines to modify this answer? – Kushan Gunasekera Jul 11 '19 at 06:19