我可以像python中的字典引用一样对象 [英] Can I variabalize an object like a dictionary reference in python
问题描述
我有一系列的词典可以持有我想结合在一起的价值观。组合是凌乱的,所以我不能仅仅结合基于键的工作的字典,并做出一些仔细的选择。当我创建这个字典时,我在表单项目#Dict中创建它们,期望在['8']中为
I have a series of dictionaries that hold values that I want to combine at the end . The combination is messy so I can't just combine the dictionaries I have to work based on keys and make some careful choices. When I created the dictionaries I created them in the form item#Dict expecting to do something like
for value in ['8','10','11','12','13','14','15','18','19','20']:
dictName='item'+value+'Dict'
但是当我快速学习dictName是一个字符串,不是我的字典的引用。
but as I quickly learned dictName is a string not a reference to my dictionary.
有没有办法使用某种模式类型的方式引用我的字典?
Is there a way to make reference to my dictionary using some pattern type approach?
我确实看到替代方法是将我的所有字典添加到列表中,然后再重复列表,这个解决方案只在我写这个问题的时候才发生。但是我有兴趣知道是否有办法实现我的原始方法。
I do see that the alternative is to add all of my dictionaries to a list as I create them and then iterate through the list- that solution only occurred to me as I was writing this question. But I am interested in knowing if there is some way to implement my original approach.
谢谢
推荐答案
eval()
可以这样做:
>>> d = {'a':'first', 'b':'second'}
>>> d == eval('d')
True
但要小心!这是一个滑坡。使用 eval()
创建安全漏洞,速度很慢,并且它鼓励意粉代码。
But be careful! It's a slippery slope. Using eval()
creates security flaws, it's slow, and it encourages spaghetti code.
内省方法 getattr
和 localals()
同样有风险。他们是强大的,他们让你做的事情将采取线和线的C ++。但是它们只能在绝对需要时使用。
The introspective methods getattr
and locals()
are similarly risky. They are powerful, and they let you do things that would take lines and lines of C++. But they should only be used when absolutely required.
在你的情况下,最好的解决方案是字典的字典,其他人已经回答了。
In your case, the best solution is a dictionary of dictionaries, as others have already answered.
这篇关于我可以像python中的字典引用一样对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!