Professional Documents
Culture Documents
Dictionaries
• A dictionary is like a list, but in a list, the index positions have to be integers; in a dictionary, the indices can
be (almost) any type.
• Dictionary is a mapping between a set of indices (which are called keys) and a set of values.
• Each key maps to a value. The association of a key and a value is called a key-value pair or sometimes an
item.
• Keys are unique within a dictionary while values may not be.
• The values of a dictionary can be of any type, but the keys must be of an immutable data type such as
strings, numbers, or tuples.
• An item has a key and the corresponding value expressed as a pair, key: value.
• While values can be of any data type and can repeat, keys must be of immutable type (string, number or
tuple with immutable elements) and must be unique.
Examples of Dictionaries
In [8]:
#empty dictionary
my_dict = {}
my_dict[1]: apple
my_dict['name']: John
Updating Dictionary
• You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or
deleting an existing entry as shown in a simple example given below.
localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 1/6
4/4/2020 Chapter_9_Dictionaries
In [9]:
my_dict[1]: pineapple
--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
<ipython-input-10-12d0928cd6b8> in <module>
1 my_dict = dict({1:'apple', 2:'ball'})
2 del my_dict[1]
----> 3 print("my_dict[1]:",my_dict[1])
KeyError: 1
Dictionary Objects
• Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or
user-defined objects. However, same is not true for the keys.
Properties of Keys
• There are two important points to remember about dictionary keys-
• (a) More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate
keys are encountered during assignment, the last assignment wins.
• (b) Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed.
localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 2/6
4/4/2020 Chapter_9_Dictionaries
In [13]:
word = 'brontosaurus'
d = dict()
for c in word:
if c not in d:
d[c] = 1
else: d[c] = d[c] + 1
print(d)
#The histogram indicates that the letters “a” and “b” appear once; “o” appears twice, a
nd so on
Dictionaries have a method called get that takes a key and a default value. If the key appears in the
dictionary, get returns the corresponding value; otherwise it returns the default value
In [12]:
100
0
We can use get to write our histogram loop more concisely. Because the get method automatically handles
the case where a key is not in a dictionary, we can reduce four lines down to one and eliminate the if
statement.
In [14]:
word = 'brontosaurus'
d = dict()
for c in word:
d[c] = d.get(c,0) + 1
print(d)
localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 3/6
4/4/2020 Chapter_9_Dictionaries
In [2]:
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
#In our else statement, we use the more compact alternative for incrementing a variabl
e. counts[word] += 1 is equivalent to counts[word] = counts[word] + 1. Either method ca
n be used to change the value of a variable by any desired amount. Similar alternatives
exist for -=, *=, and /=.
In [3]:
chuck 1
annie 42
jan 100
For example if we wanted to find all the entries in a dictionary with a value above ten, we could write the
following code:
In [4]:
annie 42
jan 100
localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 4/6
4/4/2020 Chapter_9_Dictionaries
• hash function A function used by a hashtable to compute the location for a key.
• item : Another name for a key-value pair. • key : An object that appears in a dictionary as the first part of a
key-value pair.
• lookup :A dictionary operation that takes a key and finds the corresponding value.
• nested loops: When there are one or more loops “inside” of another loop. The inner loop runs to completion
each time the outer loop runs once.
• Value: An object that appears in a dictionary as the second part of a key-value pair. This is more specific
than our previous use of the word “value”.
In [6]:
localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 5/6
4/4/2020 Chapter_9_Dictionaries
In [8]:
import string
counts = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print('count=',counts)
In [9]:
import string
string.punctuation
Out[9]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 6/6