#๐ help understanding this code
40 messages ยท Page 1 of 1 (latest)
@rocky wraith
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Is it working or not?
yes it works
ahh okay
so thing is the first for loop goes through lyrics
and the second one geos through the keys of the dictionaries
and if the repsected keys match then increment value of key by 1 each time
but the dictionary is empty
you're updating it during the for loop
so each for lop sotres words and their values
it's like dictionary.update
but this time setting key and value
why have you made artwork out of your code
in the else block
i still dont get how it can find the word in the dictionary if its empty
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict
print(lyrics_to_frequencies([apple, banana, grape, apple]))
also it doesnt seem to work
The else needs to be indented one more time
Otherwise you're doing a for ... else loop, which is also a thing, but not what you want now
It thinks that's a variable, if you want it to consider it a string (aka text), it needs to be between quotes, so "apple", "banana" etc
!e py my_dict = { "apple": 1, "banana": 4 } if "apple" in my_dict: print("apple found") if "grape" in my_dict: print("grape found (this won't print)")
@viral creek :white_check_mark: Your 3.12 eval job has completed with return code 0.
apple found
but in my other code the dictionary is empty
Yeah, if the item isn't found the else block runs, and adds the item to the dict
ok, but how can it be found if myDict = {}
if it FINDS it in the dict, it adds a frequency to it, if it DOESNT FIND, it will add the word to the dict, so that on the next loop through, it can find it
!e That's the point, it can't be found
my_dict = {}
if "apple" in my_dict:
print("won't print")
else:
my_dict["apple"] = 1 #this will run
print(my_dict) #now has apple in it```
@viral creek :white_check_mark: Your 3.12 eval job has completed with return code 0.
{'apple': 1}
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.
๐ help understanding this code