Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
loading a dictionary
#1
i get a dictionary returned from a function call. this is a bunch of variable name keys and new values for them. there are a lot of them and a very large set of variables that could be changed. i could do this by creating and loading a module using the * selection. is there a better way to do this?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Is this what you're looking for? The code below will assign values to variables according to the corresponding values in the dictionary.

tester = {'a': 7, 'b': 13, 'c': 144}

for key, value in tester.items () :
	exec (f'{key} = {value}')

print (a, b, c)
Reply
#3
At global level, you could do
globals().update(thedict)
In a class definition, you could do
locals().update(thedict)
Don't do that inside a function's body with the locals() dictionary: it won't work as you expect.

Similarly, you cannot import * inside a function's body.

Why do you want to update many variables from a dictionary?
Reply
#4
they are return values. there are just a lot of them. too many to make a tuple-like assignment. and the caller won't know which are really updated.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
You could simply update an instance's dictionary
>>> class Namespace: pass
...
>>> ns = Namespace()
>>> ns.__dict__.update({'a': 1, 'b': 10})
>>> 
>>> ns.a
1
>>> ns.b
10
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020