Can I variabalize an object like a dictionary reference in python

試著忘記壹切 提交于 2019-12-24 11:07:11

问题


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'

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.

Thanks


回答1:


eval() could do it:

>>> d = {'a':'first', 'b':'second'}
>>> d == eval('d')
True

But be careful! It's a slippery slope. Using eval() creates security flaws, it's slow, and it encourages spaghetti code.

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.




回答2:


You can use the locals function to get a dictionary containing variables in the current local scope:

>>> var0 = 7
>>> var1 = 3
>>> var2 = 4
>>> var3 = 5
>>> for i in range(4):
...    print 'var', i, 'is', locals()['var%d' % i]
... 
var 0 is 7
var 1 is 3
var 2 is 4
var 3 is 5

Although, I don't really recommend doing this. I would suggest putting your variables into a dictionary or a list, like you alluded to in your post.




回答3:


You can get the named dictionaries this way if they are attributes on an object, using getattr().

class MyClass:
    def __init__(self):
        self.item1dict = {}
        self.item2dict = {}

    def print_all_dicts(self):
        for x in [1,2]:
            print getattr(self, 'item{0}dict'.format(x))

Just be careful with this sort of metaprogramming, as it can be a slippery slope into the land of obfuscated code.



来源:https://stackoverflow.com/questions/7748596/can-i-variabalize-an-object-like-a-dictionary-reference-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!