6

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.

asheets
  • 770
  • 1
  • 8
  • 28

1 Answers1

12

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)
garlicFrancium
  • 2,013
  • 14
  • 23
n1c9
  • 2,662
  • 3
  • 32
  • 52
  • Or you could just use `list(globals().items())` to make that copy, or avoid adding new global names altogether with a generator expression: `print(*(f"{n} {v}" for n, v in globals().items()), sep="\n")` – Martijn Pieters Oct 10 '19 at 20:07
  • This does not appear to work if you have a dict in your global space. `AttributeError: 'dict' object has no attribute 'deepcopy'` – Joshua Stafford Apr 03 '21 at 13:45