我导入了一个只包含几个字典的模块。我怎样才能迭代那些?类似的东西
import moduleX as data
for d in data:
do stuff with d
这显然不起作用,因为模块不可迭代。有没有办法从模块中提取所有字典作为一个集合并遍历该集合?
我的答案:
import moduleX as data
for k, v in data.__dict__.iteritems():
if isinstance(v, dict) and not k.startswith('_'):
# do something
pass
我的 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"
...
你有没有尝试过:
for k,v in data.__dict__.items():
if isinstance(v,dict) and k not in __builtins__:
pass
您可以使用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")