在下面的代码中,我有一个字典“John”,我用某个键(“电话号码”)为其分配了一个值:
John={}
statement='John'+"['phone number']=123456"
exec statement
我之所以像上面那样使用“exec”,是因为实际字典“John”和“phone number”应该在 for 循环中变化。这可行,但不是很优雅;我宁愿做类似的事情
vars()['John'+'_phone_number']=123456
因为在这种情况下,如果语法不正确,您不会冒“exec”语句失败的风险。 (我想实现的类似于Matlab的“assignin”功能,除了字典条目)。
有没有一种不使用“exec”来定义字典条目的方法?
最佳答案
我认为您应该使用字典中的字典。您甚至可以使用 defaultdict
来避免需要为每个用户预先设置每个条目。
from collections import defaultdict
users = defaultdict(dict)
users['John']['phone number'] = 123456
关于python - 在 Python 中,动态分配字典条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23525164/