Introduction to Python Programming–
BPLCK24205B
Module-3: Dictionaries and Strings
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing,
Using Data Structures to Model Real World Things, Nested Dictionaries and Lists.
Manipulating Strings: Working with Strings, Useful String Methods, Project:
Password Locker.
Text Book: T1 Chapters: 5, 6
DICTIONARIES
Dictionaries
• Dictionaries are collection of elements
like lists
• Dictionaries have indexes to access the
elements
• Dictionary indexes are called keys and
its elements are called values
Dictionaries
• In lists the indexes must be integers only
• But, in dictionaries keys can be of any data type
Creating a dictionary
Creating a dictionary
• Syntax: dictionary_name = {‘key’ :
’value’}
• Elements of dictionary should be
enclosed within { }
• Every key is mapped to a value
Creating a dictionary
• The association of a key and a value is
called key – value pair
Creating a dictionary
• An example of creating a dictionary is as
given in the following slide
• The keys and in a dictionary should be
enclosed within ‘ ‘ if they are non-integers
• The key-value pairs should be separated
by a : (colon) while creating a dictionary
Creating a dictionary -
example
Values
Keys
Creating an empty dictionary using
dict()
• An empty dictionary can be created
using dict() fucntion
• Elements can be added to an empty
dictionary
Creating an empty dictionary
using dict()
Adding elements to a
dictionary
Adding elements to a
dictionary
• Elements can be added to an empty
dictionary or to an existing dictionary
• Syntax: dictionaryName[Key] =
value
• Keys and values should be enclosed in
quotes if they are non integers
Adding elements to an empty dictionary
Note: The order of key – value pair will differ from the
order in which these were created
Dictionaries vs. Lists
• Unlike lists, items in dictionaries are
unordered. The first item in a
listbnamed spam would be spam[0]. But
there is no “first” item in a dictionary.
• While the order of items matters for
determining whether two lists are the
same, it does not matter in what order
the key-value pairs are typed in a
dictionary
Contd ….
Contd ….
• Dictionaries are not
ordered, they can’t be
sliced like lists.
• Trying to access a key
that does not exist in a
dictionary will result in
a KeyError error
message, much like a
list’s “out-of-range”
IndexError error
message.
Contd ….
The keys(), values(), and items() Methods
keys(), values(), and items() the • spam = {'color': 'red', 'age':
values returned by these 42}
methods are not true lists. • >>> for v in spam.values():
• print(v)
They cannot be modified and do • red
not have an append() method. • 42
>>> for k in spam.keys():
But these data types (dict_keys, print(k)
dict_values, and dict_items,
>>> for i in
respectively) can be used in for color
spam.items():
loops. age
print(i)
('color', 'red')
('age', 42)
Contd . . . .
• >>> spam = {'color': 'red',
list(spam.keys()) 'age': 42}
• >>> for k, v in spam.items():
['color', 'age'] • print('Key: ' + k + ' Value: ' +
str(v))
• Key: age Value: 42
• Key: color Value: red
Checking Whether a Key or Value Exists
in a Dictionary
>>> spam = {'name': 'Zophie', 'age': 7}
• >>> 'name' in spam.keys()
False
True >>> 'color' not in
>>> 'Zophie' in spam.keys()
spam.values() True
True
>>> 'color' in spam
The get() Method
• It’s tedious to check whether a key exists in a dictionary
before accessing that key’s value.
• Fortunately, dictionaries have a get() method that takes
two arguments: the key of the value to retrieve and a
fallback value to return if that key does not exist.
Without using get(), the code
would have caused an error message
Accessing dictionaries
Accessing Dictionaries
Dictionaries are accessed using the keys as
indexes
Updating values in a
dictionary
Modifying Values in a
dictionary
• The values of any key in a dictionary can
be modified
Before:
After:
The setdefault() Method
• The first time setdefault() is called, the dictionary in
spam changes to {'color': 'black', 'age': 5, 'name':
'Pooka’}.
• The method returns the value 'black' because this is
now the value set for the key 'color’.
• When spam.setdefault('color', 'white') is called next,
the value for that key is not changed to 'white'
because spam already has a key named 'color’.
• The setdefault() method is a nice shortcut to ensure
that a key exists.
Program to count the number of
occurrences of each letter in a
string.
Output:
Pretty
Printing
• If you import the pprint module into your
programs, you’ll have access to the
pprint() and pformat() functions that will
“pretty print” a dictionary’s values.
• This is helpful when you want a cleaner
display of the items in a dictionary than
what print() provides.
Pretty
Outpu
Printing t:
The pprint.pprint() function is especially
helpful when the dictionary itself contains
nested lists or dictionaries.
Program to count the number of
occurrences of each letter in a
string without function.
The sample output would be:
Enter a string: Hello World
{'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'W': 1, 'r': 1, 'd':
1}
How to sum values of a Python
dictionary?
d = { 'foo': 10, 'bar': 20, 'baz': 30}
print(sum(d.values()))
OUTPUT:
60
Nested dictionaries
• A dictionary inside a dictionary
• A nested dictionary contains name of the dictionary
as keys
• The values are key-value pairs enclosed in {}
Creating nested dictionary
Output
Accessing a nested dictionary
Output
• Program-2
• allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham
sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}}
• def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
• print('Number of things being brought:’)
• print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
• print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
• print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
• print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham
sandwiches')))
• print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies’)))
• print(' - pretzels ' + str(totalBrought(allGuests, 'pretzels')))
• OUTPUT:
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
- pretzels 12
Introduction to Python Programming–
BPLCK24205B
Module-3: Dictionaries and Strings
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing,
Using Data Structures to Model Real World Things, Nested Dictionaries and Lists.
Manipulating Strings: Working with Strings, Useful String Methods, Project:
Password Locker.
Text Book: T1 Chapters: 5, 6