Assigning a string, integer, and so on with globals() works fine:
>>> globals()
{'__builtins__': , '__name__': '__main__', '__doc__': None, '__package__': None}
>>> globals()["a"] = 5
>>> a
5
>>> globals()
{'__builtins__': , '__name__': '__main__', '__doc__': None, 'a': 5, '__package__': None}
However, trying to assign to a dictionary fails:
>>> globals()["b['c']"] = 5
>>> globals()
{'a': 5, "b['c']": 5, '__builtins__': , '__package__': None, '__name__': '__main__', '__doc__': None}
>>> b['c']
Traceback (most recent call last):
File "", line 1, in
NameError: name 'b' is not defined
This is true even if “b” is already defined as a dictionary.
So, given a text string such as “b[‘c’]”, how do I assign b[‘c’]?
I can’t imagine what you’re trying to do here.
bdoesn’t seem to exist in globals already. You can’t assign to a dictionary that doesn’t exist.Conceivably, you could do this:
which makes
ba new dictionary containing one key,c, with a value of 5. But I’d think carefully about why you think you need to modify globals in the first place – there’s almost certainly a better way to do what you want.