You are on page 1of 6

4/4/2020 Chapter_9_Dictionaries

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.

How to create a dictionary?


• Creating a dictionary is as simple as placing items inside curly braces { } separated by comma.

• 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 = {}

#dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}
print("my_dict[1]:",my_dict[1])
#dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print("my_dict['name']:",my_dict['name'])
# using dict()
my_dict = dict({1:'apple', 2:'ball'})

#from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

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 = dict({1:'apple', 2:'ball'})


my_dict[1]='pineapple'
print("my_dict[1]:",my_dict[1])

my_dict[1]: pineapple

Deleting Dictionary Elements


In [10]:

my_dict = dict({1:'apple', 2:'ball'})


del my_dict[1]
print("my_dict[1]:",my_dict[1])

--------------------------------------------------------------------------
-
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.

Dictionary as a set of counters

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

{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}

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]:

counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}


print(counts.get('jan', 0))
print(counts.get('tim', 0))

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)

{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}

Dictionaries and files


• One of the common uses of a dictionary is to count the occurrence of words in a file with some written text.

localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 3/6
4/4/2020 Chapter_9_Dictionaries

In [2]:

fname = input('Enter the file name: ')


try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()

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 /=.

Enter the file name: test.txt


{'hi': 1, 'hello': 1}

Looping and dictionaries


• If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary. This loop
prints each key and the corresponding value:

In [3]:

counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}


for key in counts:
print(key, counts[key])

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]:

counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}


for key in counts:
if counts[key] > 10 :
print(key, counts[key])

annie 42
jan 100

localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 4/6
4/4/2020 Chapter_9_Dictionaries

• dictionary : A mapping from a set of keys to their corresponding values.

• Hashtable: The algorithm used to implement Python dictionaries.

• hash function A function used by a hashtable to compute the location for a key.

• histogram :A set of counters.

• Implementation: A way of performing a computation.

• 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.

• key-value pair: The representation of the mapping from a key to a value.

• 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]:

counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}


lst = list(counts.keys())
print(lst)
lst.sort()
for key in lst:
print(key, counts[key])

['chuck', 'annie', 'jan']


annie 42
chuck 1
jan 100

Advanced text parsing

localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 5/6
4/4/2020 Chapter_9_Dictionaries

In [8]:

import string

fname = input('Enter the file name: ')


try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()

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)

Enter the file name: test.txt


count= {'hi': 1, 'hello': 1, 'the': 3, 'coronavirus': 1, 'pandemic': 1, 'h
as': 2, 'infected': 1, 'more': 2, 'than': 2, '700000': 1, 'and': 1, 'cause
d': 1, '30000': 1, 'deaths': 1, 'globally': 1, 'with': 1, 'infections': 1,
'crossing': 1, '140000': 1, 'united': 1, 'states': 1, 'emerged': 1, 'as':
1, 'new': 1, 'covid19': 1, 'hot': 1, 'spot': 1}

In [9]:

import string
string.punctuation

Out[9]:

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

localhost:8888/nbconvert/html/Chapter_9_Dictionaries.ipynb?download=false 6/6

You might also like