我导入一个只包含多个词典的模块。我怎么能迭代那些?
的内容import moduleX as data
for d in data:
do stuff with d
这显然不起作用,因为模块不可迭代。有没有办法从模块中提取所有dicts作为集合并遍历该集合?
答案 0 :(得分:3)
我的回答:
import moduleX as data
for k, v in data.__dict__.iteritems():
if isinstance(v, dict) and not k.startswith('_'):
# do something
pass
答案 1 :(得分:0)
你试过了吗?
for k,v in data.__dict__.items():
if isinstance(v,dict) and k not in __builtins__:
pass
答案 2 :(得分: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"
...
答案 3 :(得分: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")