Iterate through each key and it's value, of a function
This question already has an answer here:
You can loop through the keys and print out the key and the value of the key using the .get
method.
for key in locals().keys():
print(key, locals().get(key))
Alternatively, you could just use indexing to get the value.
for key in locals().keys():
print(key, locals()[key])
Finally, you could also use .items()
of dictionaries. ( .iteritems()
for Python 2.x)
for key, value in locals().items():
print(key, value)
Make sure you instantiate key
and value
before you use these variables. Otherwise, you will change the items inside locals()
while iterating and you will get an error.
While @VictorC's for key, value in locals().items()
worked, I found that this does too:
for key, value in zip(locals().keys(), locals().values()):
print (key, value)
(Just noting this here for the record. I'm still learning python, so I'm very open to someone commenting on the difference in zip()
vs. looping through items()
if they are bored).
上一篇: 循环使用字典并获取密钥
下一篇: 遍历每个键,它是一个函数的值