document = "This is a massive document" word_Counts = {} #New dictionary for word in document: if word in word_Counts: word_Counts[word] += 1 #pretty simple, increase the word count if the key 'word' exists in word_Counts dict else: word_Counts[word] = 1 #Wait, it doesn't exist... we don't explicity create a new key of 'word'. But apparently this statement creates the key and value! #So... why can't we just keep using word_counts[word] += 1, shouldn't that create the key/value? It's assignment as well as the statement 1word_counts[word] = 1 # So let's see what 'word_counts[word]' does by itself, should it create a key with no value? It might not even be a statement. word_Counts["Posthumously"] #It throws a KeyError: 'Posthumously'! #WTF
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question