-1

I'm trying to assign the values of a nested dictionary to variables named after their key. I found this code on Stackoverflow but it only prints the key and value pair:

def myprint(d):
for k, v in d.items():
    if isinstance(v, dict):
        myprint(v)
    else:
        print("{0} : {1}".format(k, v))

I would like it so that for example, if I have the following in my dictionary: {thisIsADummy : 37}

I can somehow create a variable named thisIsADummy, named after the key, with the value 37 So my input ould be print(thisIsADummy) and the output would be 37

Please let me know if anybody has any ideas on how to do this as efficiently as possible, because this dictionary has probably over a thousand pairs. Thank you.

EDIT: Using exec works well, but I oversimplified in the original post. I need the variable to be a dictionary so when I open multiple files I can append values.

  • YOU SHOULD NOT DO THIS: Having said that, this should work `globals().update(dictionary)` as `globals()` is just a dict and you can update it just like a dict – Iain Shelvington Aug 05 '20 at 03:33
  • @IainShelvington I don't understand what this does. – Matthew Kaplan Aug 05 '20 at 03:36
  • I think exec is what I was thinking of, not eval [Convert string to variable name in python](https://stackoverflow.com/questions/19122345/convert-string-to-variable-name-in-python). It's also a bad idea `exec("x = 3")` – Trenton McKinney Aug 05 '20 at 03:38
  • @MatthewKaplan `globals()` is a dict like object that contains all of your current global variables. This globals object is mutable so instead of doing `a = 1` you could do `globals()['a'] = 1`. I highly recommend against doing this though as it will make your code hard to reason about and likely run into weird and unexpected issues – Iain Shelvington Aug 05 '20 at 03:41
  • `{thisIsADummy : 37}`, should it be `{"thisIsADummy" : 37}`? – jizhihaoSAMA Aug 05 '20 at 03:43

2 Answers2

1

Avoid using eval(),Try setattr(I am not sure whether it is a better way.):

import sys

d = {"thisIsADummy": 37, 'a': [123,2]}
for k, v in d.items():
    setattr(sys.modules[__name__], k, v)

a.append(1)
print(thisIsADummy, a)

Result:

37 [123, 2, 1]
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • Unfortunately, I oversimplified my original post because I didn't think it would matter much, but I'm actually going to be opening multiple files so it would help if the variable was a list so I could append values. Do you have any ideas how best to accomplish this? – Matthew Kaplan Aug 05 '20 at 03:53
  • @MatthewKaplan It would be okay if your value is a list. – jizhihaoSAMA Aug 05 '20 at 04:03
  • How would I append values? The original variable is an int. – Matthew Kaplan Aug 05 '20 at 04:04
1

Basic idea is to use 'exec' function like below.

nat = {
    'abc': 1,
    'a123': 2,
    'a1b': 3,
    'b31': 4
}

for k, v in nat.items():
    exec("%s = %d" % (k, v))
    print(k, v)

print(abc, a123, a1b, b31)

Note: It will only work if keys follows the variable name constraints

  • Stupid Jupyter Notebook had the variable stored. `for k, v in t.items(): exec(f'{k} = v')` – Trenton McKinney Aug 05 '20 at 03:57
  • @GauravVijayvargia thanks for the suggestion. It actually works and saves it in a variable which is great. Unfortunately, I oversimplified my original post because I didn't think it would matter much, but I'm actually going to be opening multiple files so it would help if the variable was a list so I could append values. Do you have any ideas how best to accomplish this? – Matthew Kaplan Aug 05 '20 at 04:01
  • @MatthewKaplan If I understand your problem correctly then this will help 'exec("%s = [%d]" % (k, v))'. It will create key strings as list variable – Gaurav Vijayvargia Aug 05 '20 at 04:06
  • @GauravVijayvargia unfortunately this will not work for me because the value is not always an int %d only accepts ints. Is there a way to change this so it accepts all types? I was actually just using `exec('k=v')` before which worked for me. If I was only using ints this would work perfectly. – Matthew Kaplan Aug 05 '20 at 04:09
  • @MatthewKaplan try 'exec("%s = ['%s']" % (k, v))'. – Gaurav Vijayvargia Aug 05 '20 at 04:13
  • @MatthewKaplan if you want to use the exact type, then you might have to use if else conditions on types – Gaurav Vijayvargia Aug 05 '20 at 04:16