






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Strings can be dictionary keys: mydict = {"dog":"Hund", "rhinoceros":"Nashorn"} Integers can be dictionary keys. The following dictionary (somewhat redundantly) maps prime numbers to their rank, e.g. 2 is the first prime number. prime_nums = {2:1, 3:2, 5:3, 7:4, 11:5} Floating point numbers can be dictionary keys as well: >>> mydict = {3.1415 : "pi", 2.71828 : "e" } >>> mydict[3.1415] 'pi’ Lists cannot be dictionary keys – more on this later: >>> mydict = {[1,2] : "wont_work"} Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list'
paragraph = ”””While dieters are accustomed to exercises of will, a new English translation of Germany's most popular diet book takes the concept to a new philosophical level. The Nietzschean diet, which commands its adherents to eat superhuman amounts of whatever they most fear, is developing a strong following in America.””” counts = { } for word in paragraph.split(): if not(counts.has_key(word)): counts[word] = 0 counts[ word ] = counts[ word ] + 1 for word in counts.keys(): print word, counts[word] counts.has_key(word) is a conditional that is true if the dictionary ‘counts’ has a key that is the same as the contents of the variable ‘word’. counts.keys() yields the list of keys of the dictionary ‘counts’.
Iterating over two things at once? We get back to this in a minute.
>>> mydict[ [1,2] ] = "one two” Traceback (most recent call last): File "", line 1, in? TypeError: list objects are unhashable
You can access the dictionary value for a given key using straight brackets: >>> mydict = { “dog” : “Hund”, “rhinoceros” : “Nashorn”} >>> mydict[‘dog’] ‘Hund’ You can also use get(): >>> mydict.get(‘dog’) ‘Hund’ The advantage of get() is that you can give a default: >>> mydict['butterfly'] Traceback (most recent call last): File "", line 1, in KeyError: 'butterfly' >>> mydict.get('butterfly', 'Schmetterling') 'Schmetterling’