Lets say I have the following code
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
def test_function():
resources['water'] = 500
test_function()
print(resources)
The program compiles and prints out: {‘water’: 500, ‘milk’: 200, ‘coffee’: 100}
Great!
Now lets say I have another piece of code:
test_variable = 0
def test_function():
test_variable = 1
test_function()
print(test_variable)
It prints out: 0. Now I know what you are going to say: You need to use the ‘global’ keyword so the test_function changes to test_variable to 0. Well it seems you don’t need the global keyword for dictionaries. Why is that? And I’m not looking for a deep technical explanation. Wouldn’t you agree that people who are new to code/Python would intuitively think that a dictionary would also need a ‘global’ keyword?
Daffy Raffy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.