Reputation: 684
So I have a function that takes two dictionaries, adds them together.
from collections import Counter
def ReportTwoAddedDictionaries(DictOne,DictTwo):
Dict1 = Counter(DictOne)
Dict2 = Counter(DictTwo)
DictTotal = Dict1 + Dict2
print DictTotal
DictTotal = dict(DictTotal)
print DictTotal
return DictTotal
When I run the function:
ReportTwoAddedDictionaries(FreePoints,FlyPoints)
it prints out DictTotal correctly (as it is told to do inside the function). However, when I try outside of the function, after running it, it prints empty
print DictTotal
Any idea why DictTotal is returning empty, but prints fine from within the function? Thank you.
Upvotes: 0
Views: 140
Reputation: 16930
Or you can define DictTotal as global variable, which is visible outside the function scope, but its less recommended.
from collections import Counter
def ReportTwoAddedDictionaries(DictOne,DictTwo):
global DictTotal
Dict1 = Counter(DictOne)
Dict2 = Counter(DictTwo)
DictTotal = Dict1 + Dict2
print DictTotal
DictTotal = dict(DictTotal)
print DictTotal
return DictTotal
ReportTwoAddedDictionaries({1: 2},{'1' : '3'})
print DictTotal
Upvotes: 0
Reputation:
When you call this method:
ReportTwoAddedDictionaries(FreePoints,FlyPoints)
The returned value isn't stored anywhere. What you see being printed is the print
inside the function.
When you call print DictTotal
outside the function, it should throw an error, unless you've previously declared that variable.
If you store the returned variable in the current scope, like this:
DictTotal = ReportTwoAddedDictionaries(FreePoints,FlyPoints)
print DictTotal
You should see the dictionary printed as requested.
Upvotes: 0
Reputation: 308111
You need to capture the return value. A return statement doesn't just magically create a new variable in the caller's space.
DictTotal = ReportTwoAddedDictionaries(FreePoints,FlyPoints)
P.S. There's no need for the variable you use for the return value to be the same name as the one returned from the function.
foo = ReportTwoAddedDictionaries(FreePoints,FlyPoints)
print foo
Upvotes: 2