how to use loop to get values in dir()?

∥☆過路亽.° 提交于 2019-12-02 08:46:13

问题


Why i can't get the values in the items in dir() with loop:

for item in dir():
    print(item)

It just print

 __builtins__
 __doc__
 __loader__
 __name__
 __package__
 __spec__

So, how can i use loop to print the value in item, i.e "__main__" in __name__ Thanks!


回答1:


Calling dir without the argument is logically equivalent to list(locals()), as in getting the list of names of variables in the current namespace (keys of locals() dictionary).

You'd use the items method of locals() instead:

In [5]: for name, value in list(locals().items()):
   ...:     print(name, value)
   ...: 



回答2:


vaultah's answer is best, I think, but you could also use eval to get the values:

for item in dir():
    print('{} : {}'.format(item, eval(item)))

There is usually a lot of stigma regarding the use of eval (it's dangerous!) and I will probably be downvoted for this answer, however, I think that it OK in this limited case.



来源:https://stackoverflow.com/questions/28379099/how-to-use-loop-to-get-values-in-dir

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