0% found this document useful (0 votes)
1 views

Modue 3 - Dictionaries

The document provides an overview of dictionaries in Python, explaining their structure, creation, and key-value pairs. It highlights differences between dictionaries and lists, including unordered items and methods for accessing and modifying values. Additionally, it covers nested dictionaries, the use of the setdefault() method, and practical examples for counting occurrences of letters in a string.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Modue 3 - Dictionaries

The document provides an overview of dictionaries in Python, explaining their structure, creation, and key-value pairs. It highlights differences between dictionaries and lists, including unordered items and methods for accessing and modifying values. Additionally, it covers nested dictionaries, the use of the setdefault() method, and practical examples for counting occurrences of letters in a string.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Programming in Python

21CSE23
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 values 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() function
• 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 list named
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, color
>>> for i in
respectively) can be used in for age
spam.items():
loops.
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}


>>> 'color' not in
spam.keys()
True
>>> 'name' in spam.keys()
True
>>> 'Zophie' in
spam.values()
True
>>> 'color' in spam

False
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:
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}
The setdefault() Method

• You’ll often have to set a value in a


dictionary for a certain key only if that
• key does not already have a value.
• Normal way:
• spam = {'name': 'Pooka', 'age': 5}
• if 'color' not in spam:
• spam['color'] = 'black‘
The setdefault() method offers a way to do
this in one line of code.

The first argument passed to the method is


the key to check for, and the second
argument is the value to set at that key if the
key does not exist.

If the key does exist, the setdefault() method


returns the key’s value.
• >>> spam = {'name': ‘Global', 'age': 5}
• >>> spam.setdefault('color', 'black')
• 'black'
• >>> spam
• {'color': 'black', 'age': 5, 'name': ' Global'}
• >>> spam.setdefault('color', 'white')
• 'black'
• >>> spam
• {'color': 'black', 'age': 5, 'name': ' Global‘}
• 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.
How to sum values of a Python
dictionary?

d = { 'foo': 10, 'bar': 20, 'baz': 30}

print(sum(d.values()))

OUTPUT:
60
Using Data Structures to Model
Real-World Things

1. Chess Board.

2. A Tic-Tac-Toe Board.
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

You might also like