Print all variables and their values

This question was asked quite a bit, and I tried every solution that I came across, but had no success. I am trying to print each variable and its value using the following two lines.

for name, value in globals():
    print(name, value)

This gives an error: Too many values to unpack When I run:

for name in globals():
    print(name)

I get only variable names. Any help would be greatly appreciated.

+4
source share
1 answer

globals()returns a dict- therefore, to iterate through the 21> key / value pairs, you call it a items()method:

dog = 'cat'
>>> for name, value in globals().items():
...     print(name, value)
... 
('__builtins__', <module '__builtin__' (built-in)>)
('__name__', '__main__')
('dog', 'cat')
('__doc__', None)
('__package__', None)
>>> 

This is explained in the documents for Data Structures available here!

Python 3 version:

for name, value in globals().copy().items():
    print(name, value)

if we do not copy the output functions of the globals, then there will be a RuntimeError.

, , deepcopy() copy()

for name, value in globals().deepcopy().items():
    print(name, value)
+6

Source: https://habr.com/ru/post/1686726/


All Articles