The result of the string executed by the built-in function exec is not as expected.

>>>a = {}
>>>b = "c"
>>>a[b] = 2

>>>a
{"c": 2}

execute the above statement normal assignment, instead, use exec to execute the string

>>>exec(f"a = {{}}")    -sharp
>>>exec(f"b = "c"")    -sharp
>>>exec(f"{a}[{b}] = 2")    -sharpa

>>>a
{}

ask why this happens. Sometimes undefined situations such as NameError will occur when exec executes other strings. Please tell me how to change the above exec statement to match the expected statement

.
Mar.04,2021

I don't really know what the question means.

>>> exec("a={}")
>>> exec("b='c'")
>>> exec("a[b]=2")

clipboard.png


is analyzed in two blocks,
first block, f-string string formatting
second block, exec function

exec(f"a = {{}}") 

is equivalent to exec ("a = {}"), and an is {}

after execution
exec(f"b = 'c'") 

b is'c'

after execution
exec(f"{a}[{b}] = 2") 

is equivalent to exec ("{} [{c}] = 2"), then two problems arise:
first, if c is not defined, it will be reported to NameError: name 'c' is not defined
. Second, if the added object is {} instead of a br a, it will not change.
should be modified to

exec(f"a['{b}'] = 2")

is equivalent to exec (f "a ['c'] = 2")

in the last digression, it is not recommended to use exec, especially f-string in exec.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e47395-4cfb5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e47395-4cfb5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?