在Python中,动态分配字典条目(In Python, assign entries of dictionaries dynamically)

编程入门 行业动态 更新时间:2024-10-13 06:21:12
在Python中,动态分配字典条目(In Python, assign entries of dictionaries dynamically)

在下面的代码中,我有一个字典“John”,我用一个键(“电话号码”)分配一个值:

John={} statement='John'+"['phone number']=123456" exec statement

我之所以选择“exec”,是因为实际字典“John”和“电话号码”应该在for循环中变化。 这有效,但不是很优雅; 我宁愿做类似的事情

vars()['John'+'_phone_number']=123456

因为在这种情况下,如果语法不正确,则不会冒“exec”语句失败的风险。 (我想要实现的是类似于Matlab的“assignin”函数,除了字典条目)。

有没有一种方法可以在不使用“exec”的情况下定义字典的条目?

In the code below, I have a dictionary "John" which I assign a value to with a certain key ("phone number"):

John={} statement='John'+"['phone number']=123456" exec statement

The reason I did it with "exec" like above is because the actual dictionary "John" and "phone number" are supposed to vary within a for loop. This works, but is not very elegant; I'd rather like to do something similar to

vars()['John'+'_phone_number']=123456

because in this case, you don't run the risk of the "exec" statement failing if the syntax is not right. (What I'd like to achieve is similar to Matlab's "assignin" function, except for dictionary entries).

Is there a way of defining entries of a dictionary without using "exec"?

最满意答案

我想你应该使用字典词典。 您甚至可以使用defaultdict来避免需要为每个用户预先设置每个条目。

from collections import defaultdict users = defaultdict(dict) users['John']['phone number'] = 123456

I think you should use a dictionary of dictionaries. You can even employ a defaultdict to avoid needing to precondition each entry for each individual user.

from collections import defaultdict users = defaultdict(dict) users['John']['phone number'] = 123456

更多推荐

本文发布于:2023-08-02 08:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1373093.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条目   字典   动态分配   Python   dynamically

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!