python - 在 Python 中,动态分配字典条目

标签 python dictionary

在下面的代码中,我有一个字典“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/

相关文章:

python - 循环内循环 python

python - 如何使用 numpy 数组正确调用 `__rsub__` ?

javascript - 从 javascript 中的 xml 文件在谷歌地图上添加标记

python - Mongoengine PointField 给出预期的位置对象,位置数组格式不正确错误

python - 如何在Sqlalchemy中为各种模型写一个通用的get_by_id()方法?

dictionary - Swift:如何在字符串表达式中打印出字典键的值?

python - 每个键都有唯一可能值的字典?

Python字典理解

python - 在 Python 中将 QVariant 转换回 dict

python - 如何在给定不需要的字符列表的情况下去除字符串? Python