2

For a dictionary d={'foo1': 1, 'foo2': 2, 'foo3': 3}, what is the most efficient way to assign the strings to their definitions:

foo1=1
foo2=2
foo3=3

When no assignment statements are used, I need to call the entry with the dictionary, eg. d['foo1'], but I don't plan to use this.

Note: Thanks for pointing out that it was a string. However, I am now assigning the string terms to their corresponding values in the dictionary.

2

2 Answers 2

4
d = {'a': 1, 'b': 2}
locals().update(d)
Sign up to request clarification or add additional context in comments.

6 Comments

Nice pointing out update(), was unaware that it took a dictionary : )
This doesn't work. Locals only gives you a view. You cannot use it to add, delete or change the contents of a variable. You can mutate a referenced object, but that's different. docs.python.org/3/library/functions.html#locals
Does globals make a difference?
Yes. Globals are stored in a dict internally. Globals just gives you access to that dict. Locals are stored differently. The function creates a dict from the underlying storage implementation.
Then you're fine. But that means you can't use dict.update. You have to do stuff like: locals()[name].attr = new_value. It makes your implementation fragile. Just use a dict and stop trying to force locals to do something it's not meant for. If you really must, then create an object and update its internal __dict__. Eg. obj.name becomes vars(obj)["name"]
|
3
>>> globals()['test'] = 10
>>> test
10

Not the most pretty way, but it works.

d = {'foo1': 1, 'foo2': 2, 'foo3': 3}
for key, val in d.items():
    globals()[key] = val
print(foo1)

(Or use locals(), but Colin beat me to it)

2 Comments

May I understand how 'test' relates to my examples above?
@teachmyselfhowtocode It was a example of how you can assign variables via "strings", your solution is the two rows below. The first was just a test so you can see the principle of how it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.