dict
ionary
(and class
dictionary
view)
in the
Python
Standard Library
dict
in the
Python
Standard Library:
A
for
loop
(line
26)
can have an
else
section
(line
30).
Please type a note (e.g., do): so So, a needle pulling thread. Please type a note (e.g., do): me Me, a name I call myself. Please type a note (e.g., do): tee Sorry, "tee" is not a note.
A
dict
ionary
is like a
list
or
tuple
that contains two parallel columns.
The left column is the column of
keys.
The right column is the column of
values.
The two columns must contain the same number of items.
We look up a key in order to find the corresponding value.
In the following example,
the keys are
str
ings
and the values are
str
ings.
But in another
dict
ionary,
the keys and values could be other data types.
For example, the keys could be
str
ings
and the values could be
int
s.
In real life,
however,
the keys will usually be
str
ings.
Please type a note (e.g., do): so So, a needle pulling thread. Please type a note (e.g., do): me Me, a name I call myself. Please type a note (e.g., do): tee Sorry, "tee" is not a note.
do2.py
with the following
LBYL
code.
if note in notes: #if note is one of the keys of the dict: definition = notes[note] #could also say definition = notes.get(note) print(f"{note.capitalize()}, a {definition}.") else: print(f'Sorry, "{note}" is not a note.') print()
Why does Python have the function
get
that does (almost) the same thing as the
[
square brackets]
?
See exercise 4 below.
dict
ionary.
You can use each key to get the corresponding value.
This
for
loop and the ones below with
items
print all the items in the
dict
ionary,
and Python 3.7 even guarantee that the items will be printed
in the order in which they were inserted.
But if you frequently loop through the
dict
ionary,
or frequently rearrange the order of its items,
it might be faster to use a
collections.OrderedDict
.
for key in notes: #could also say for key in notes.keys(): print(key, notes[key])
do deer, a female deer re drop of golden sun me name I call myself fa long, long way to run so needle pulling thread la note to follow so ti drink with jam and breadIf all you want are these keys and values in their original order, exercise 6 below is a simpler way to loop through them.
dict
ionary
are
str
ings,
their sorted order is alphabetical order,
not numerical order.
The
sorted
function returns a
list
of
str
ings,
even though
notes
is a
dict
.
for key in sorted(notes): print(key, notes[key])
do deer, a female deer fa long, long way to run la note to follow so me name I call myself re drop of golden sun so needle pulling thread ti drink with jam and bread
dict
ionary
are
str
ings,
their sorted order is alphabetical order,
not numerical order.
for key in sorted(notes, key = notes.get): print(key, notes[key])
do deer, a female deer ti drink with jam and bread re drop of golden sun fa long, long way to run me name I call myself so needle pulling thread la note to follow so
def score(key): "Return the length of the value corresponding to this key." return len(notes.get(key)) for key in sorted(notes, key = score): print(key, notes[key])Or with a lambda function:
for key in sorted(notes, key = lambda key: len(notes.get(key))): print(key, notes[key])
la note to follow so re drop of golden sun me name I call myself do deer, a female deer fa long, long way to run so needle pulling thread ti drink with jam and bread
items
returns a
list
of
tuple
s
(or at least an
iterable
of
tuple
s).
Each of these
tuple
s
consists of a key and the corresponding value.
for item in notes.items(): #item is a tuple. print(item[0], item[1]) #item[0] and item[1] are strings.
do deer, a female deer re drop of golden sun me name I call myself fa long, long way to run so needle pulling thread la note to follow so ti drink with jam and breadWe could also write the loop this way. We saw a two-variable
for
loop with
enumerate
in
For char,
and with
zip
in
Zip.
The parentheses immediately after the word
for
are optional.
for (key, value) in notes.items(): print(key, value)
do deer, a female deer re drop of golden sun me name I call myself fa long, long way to run so needle pulling thread la note to follow so ti drink with jam and bread
dict
ionary
googletrans.LANGCODES
.
pip3 install googletrans
""" Print the iso639-1 language codes. Parens around (key, value) are required. """ import sys import googletrans for key, value in googletrans.LANGUAGES.items(): print(f"{key:5} {value}") sys.exit(0)
af afrikaans sq albanian am amharic ar arabic hy armenian etc. he Hebrew
""" Print the iso639-1 language codes. """ import sys import googletrans #Parentheses necessary around key, value. for i, (key, value) in enumerate(googletrans.LANGUAGES.items(), start = 1): print(f"{i:3} {key:5} {value}") sys.exit(0)
1 af afrikaans 2 sq albanian 3 am amharic 4 ar arabic 5 hy armenian etc. 106 he Hebrew
dict
ionary
is
http.server.BaseHTTPRequestHandler.responses
;
see
One
big sequence of bytes.
Each value in this
dict
ionary
is a
tuple
of two
str
ings,
value[0]
and
value[1]
.
import http.server for key, value in http.server.BaseHTTPRequestHandler.responses.items(): print(int(key), value[0]) if value[1]: #or if value[1] != "": print(value[1]) print()
100 Continue Request received, please continue 101 Switching Protocols Switching to new protocol; obey Upgrade header 102 Processing 200 OK Request fulfilled, document follows 201 Created Document created, URL follows
dict
ionary
whose keys and values are names and phone numbers.
directory = { "John": "212-234-5678", "Sally": "914-876-5432", #etc.
dict
ionary
that translates
IKEA language
into English.
(Or vice versa.)
dict
ionary
loosely based on the story about the international symposium on elephants.
The German scholar presented a paper entitled
Some Observations Preliminary to the Compilation of a Definitive
Bibliography on the Elephant.
The French scholar presented a paper called
The Love Life of the Elephant.
The Englishman presented
Hunting and Trapping the Elephant in his Native Habitats
and the American team offered
How to Grow Bigger and Better Elephants.
Finally, the Polish scholar ended the conference with a paper entitled
The Elephant and the
Polish
Question.
(Alternative ending:
The Elephant and the
Jewish
Question.)
dict
ionary
must be
hashable.
See
hash
and
__hash__
.
import sys #See if a string is hashable. s = "hello" #also try s = [10, 20, 30] #also try s = {10, 20, 30} try: h = hash(s) except TypeError as error: print(f"Sorry, an object of {type(s)} is not hashable:", error, file = sys.stderr) else: print(f"An object of {type(s)} is hashable, and this object hashed to {h:,}.")
An object of <class 'str'> is hashable, and this object hashed to 2,110,794,038,273,648,352.
Sorry, an object of <class 'list'> is not hashable: unhashable type: 'list'
Sorry, an object of <class 'set'> is not hashable: unhashable type: 'set'