Keefer
Keefer

Reputation: 11

Python3 function to map lists into dictionary

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

Answers (2)

Austin
Austin

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)


Or, there is one another way which I won't recommend, but only FYI.

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

msi_gerva
msi_gerva

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

Related Questions