What is the best way to convert Dictionary keys into variables with the dictionary values?

Viewed 1355

Can I convert dictionaries into variable-value pairs without globals or locals or exec, like:

count = { 'one':'first', 'two':'second'}
for key in count.keys():
    key = count.get(key)

Then I need:

print(one)
'first'

But it's not happening. can I do this? How?

4 Answers

I found this on Quora, worked for me. Credit goes to Thu Yein Tun.

count = { 'one':'first', 'two':'second'}
for k, v in count.items():
    vars()[k] = v

https://qr.ae/pGBmlX

If you are willing to create an object, you can then use getattr and setattr to add and get its attributes much as you can with variables.

class Values(object):
    pass

obj = Values()

count = {'one':'first', 'two':'second'}

for key, value in count.items():
    setattr(obj, key, value)

print(getattr(obj, 'one'))
print(getattr(obj, 'two'))

# first
# second

You can use this:

for k,v in count.items():
    exec(f"{k}={repr(v)}")

example:

count = { 'one':'first', 'two':'second'}
for k, v in count.items():
    exec(f"{k}={repr(v)}")
print(one, two)

I don`t understand why you would want to dynamically create variables, but in this case just use the keys from the dictionary as if you would have declared variables.

print(count.get("one","Unknown"))

The get function on a dictionary will handle KeyErrors and return a default value, which is specified in param 2. In this case it will look for key "one" in the count dict and then return the value, else it will return "Unknown". If parameter 2 is left blank, a null value will be returned

Related