1

我导入了一个只包含几个字典的模块。我怎样才能迭代那些?类似的东西

import moduleX as data
for d in data:
    do stuff with d

这显然不起作用,因为模块不可迭代。有没有办法从模块中提取所有字典作为一个集合并遍历该集合?

4

4 回答 4

3

我的答案:

import moduleX as data

for k, v in data.__dict__.iteritems():
    if isinstance(v, dict) and not k.startswith('_'):
        # do something
        pass
于 2012-10-10T09:29:13.180 回答
0

我的 2 美分解决方案:

>>> for item in dir(data):
...     print item
...     if eval('type(t.'+item+')') is dict: print item, "is a dict"
... 

或更好:

>>> for item in dir(data):
...     if eval('isinstance(data.'+item+', dict)') and not item.startswith('_'): 
            print item , "is a dict"
... 
于 2012-10-10T09:24:40.240 回答
0

你有没有尝试过:

for k,v in data.__dict__.items():
    if isinstance(v,dict) and k not in __builtins__:
        pass
于 2012-10-10T09:23:12.657 回答
0

您可以使用vars(object)

import the_module_with_dictionaries as my_mod

#Get just names of defined dictionaries
for case in vars(my_mod):
    print(case)

#Get the values in those dictionaries
for case in vars(my_mod).values():
    print(case)

    if isinstance(case, dict):
        print("Yay found a dict")
于 2017-01-24T02:31:20.967 回答