Reputation: 11
I have this block of code:
dict1 = ['aa','bb','cc','dd']
dict2 = ['11','22','33','44']
newDict = {}
def map_lists(Dict1, Dict2):
newDict=dict(zip(dict1, dict2))
print(newDict)
map_lists(dict1, dict2)
print(newDict)
I want to update the "newDict" dictionary, but I can only get to the function to print out the mapping from inside the function.
Can anyone spot my mistake?
Upvotes: 1
Views: 45
Reputation: 26057
You need to return
from function.
When you do newDict = dict(zip(dict1, dict2))
within a function, a new dictionary is created whose scope is local to the function and is not accessible outside.
If you are likely to use this dictionary outside of function, the suggested way is to return the new dictionary back to caller once the function is done.
dict1 = ['aa','bb','cc','dd']
dict2 = ['11','22','33','44']
def map_lists(Dict1, Dict2):
newDict = dict(zip(dict1, dict2))
return newDict
newDict = map_lists(dict1, dict2)
print(newDict)
dict1 = ['aa','bb','cc','dd']
dict2 = ['11','22','33','44']
def map_lists(Dict1, Dict2):
global newDict
newDict=dict(zip(dict1, dict2))
map_lists(dict1, dict2)
print(newDict)
global
is not advised to use as it's not a good programming practice in any language.
Upvotes: 1
Reputation: 2078
I would do this like this:
dict1 = ['aa','bb','cc','dd']
dict2 = ['11','22','33','44']
def map_lists(Dict1, Dict2):
newDict = {}
newDict=dict(zip(dict1, dict2))
return newDict
newDict = map_lists(dict1, dict2)
print(newDict)
Upvotes: 0