This question has been asked quite a bit, and I've tried each solution I come across, but haven't had any success. I'm trying to print out every 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 only get the names of the variables. Any help would be appreciated.
globals()
returns a dict
- so, to iterate through a dict
's key/value pairs, you call it's 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 within the docs 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 globals functions then there will be RuntimeError.
Also if there are list and dictionaries in the output of some variable then use deepcopy() instead of copy()
for name, value in globals().deepcopy().items():
print(name, value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With