0
Why the function definition does not return anything?
I wanted to improve the simple Text Analyzer program, but my functions do not return anything. Only addToDict returns myDict, the functions filter and sort seem to not return anything, because the values displayed by display are the same that the addToDict returns. Please help. The txt is just random letters. https://code.sololearn.com/cLsC05Fa7yRK/?ref=app
8 ответов
+ 2
Those functions do return something, it's just that you don't save that return value to anything, so it is lost.
myDict = filterDictionary(myDict)
and
myDict = sortDictionary(myDict)
should help you out...
The difference between those and addToDict is subtle but important. Since a dictionary is mutable, any changes you make to it inside a function are kept when the function is finished. So dictionary[key] = value is adding the key: value pair to the dictionary passed to the function.
In the other two, however, you say dictionary = {...}, this is creating an entirely new dictionary inside the function. Once the function had ceased, the variable 'dictionary' ceases to exist, and since you don't save the return value (as explained above), you get this behaviour.
+ 2
I've just tried this:
myDict = {2: [1,2,3], 5:[0,1,2], 0:[1,2,3,4]}
newDict = dict(filter(lambda elem: elem[1][0] > 0 , myDict.items())) #{2: [1, 2, 3], 0: [1, 2, 3, 4]}
This seems to work just as you wanted, so I'm not really sure what was happening. I guess I wouldn't be able to diagnose the issue without seeing the code as it was 🤷🏼♂️
+ 2
Russ I've also tried it one more time and... It worked. It seems like everything wasn't working properly because of the previous mistakes that I've made. Thank you very much for help, I really appreciate the time you've spent to write me an answer. Lots of stuff is clear for me now 😊
+ 2
No problem at all. Glad I could help!
+ 1
Hopefully this code snippet will demonstrate my point.
def add():
dct[1] = 0
dct = {}
add()
print(dct) #{1: 0}
def add2():
dct = {1: 0}
return dct
dct = {}
add2()
print(dct) # {}
dct = add2()
print(dct) # {1: 0}
0
Russ thank you very much now I understand why these returns "didn't work" ! ☺️
0
Filip Szczybura 👍 No worries!
0
Russ also I have a question regarding filtering the dictionary. I've tried to put the filter function into my code with no results.
newDict = dict(filter(lambda elem: elem[1][0] > 0 , myDict.items()))
It resulted in TypeError. As you can see in my code, as a value I have a list. So I wanted to filter the values[0], in my case count, only that are greater than 0. It didn't work that's why I decided to use a dictionary comprehension. But could you explain me why it gives me a Type Error? It works without dict at the beginning. So it seems like I cannot store the result in the form of dictionary?