Dictionaries and Structuring
Data
2
The Dictionary Data Type
Like a list, a dictionary is a collection of many values.
But unlike indexes for lists, indexes for dictionaries can use many different data types, not just
integers.
Indexes for dictionaries are called keys, and a key with its associated value is called a key-value pair
Key Features of Dictionaries:
Unordered: Unlike sequences such as lists or tuples, dictionaries do not maintain any specific order of
elements.
Mutable: Dictionaries are mutable, meaning you can modify, add, or remove key-value pairs after creating
the dictionary.
Keys and Values: Each key in a dictionary must be unique, while values can be duplicated. Keys are used
to access the corresponding values in the dictionary.
3
Creating a Dictionary:
You can create a dictionary using curly braces {} and specifying key-value pairs separated by colons :
Ex: person = {
"name": “Arun",
"age": 25,
"city": “Mysuru"
}
In this example, "name", "age", and "city" are the keys, and “Arun", 25,
and “Mysuru" are the corresponding values.
Accessing Values:
You can access the values in a dictionary by using their keys inside square brackets []. 4
Here's an example:
print(person["name"]) # Output: Arun
print(person["age"]) # Output: 25
Modifying and Adding Elements:
You can modify the value associated with a specific key or add new key-value pairs to a dictionary.
Examples:
person["age"] = 30 # Modifying the value
person["occupation"] = “Teacher" # Adding a new key-value pair
NOTE: Dictionaries can still use integer values as keys, just like lists use integers for indexes, but they do
not have to start at 0 and can be any number.
spam = {12345: 'Luggage Combination', 42: 'The Answer'}
Code:
>>>person = { "name": “Arun", "age": 25,"city": “Mysuru“ } 5
>>>for v in [Link]():
print(v)
OUTPUT:
Arun
25
Mysuru
>>>person = { "name": “Arun", "age": 25,"city": “Mysuru“ }
>>>person["age"]=30 #Modifying
>>>person["occupation"]=“Teacher“ #Adding
>>>for v in [Link]():
print(v)
OUTPUT:
Arun
30
Mysuru
Teacher
6
Dictionaries vs. Lists
Ex:
spam = ['cats', 'dogs', 'moose’] 2 lists Let's break down the comparisons:
my_cats =['dogs', 'moose', 'cats']
1. spam and my_cats have the
spam == my_cat
same elements, but in a different
False
order. Therefore, when comparing
animal = {'name': 'Zophie', 'species': 'cat', 'age': '8’}
2 dictionaries
them using the == operator, the
pets = {'species': 'cat', 'age': '8', 'name': 'Zophie’}
result is False. The order of
animal == pets
elements matters in list
True
comparisons.
2. animal and pets have the same key-value pairs, even though the order of the key-value pairs is
different. In Python dictionaries, the order of key-value pairs is not significant. When comparing
dictionaries using the == operator, the result is True if they contain the same key-value pairs, regardless
of the order.
7
The keys(), values(), and items() Methods
keys():
• The keys() method allows you to access the keys of a dictionary.
• Keys are like labels or identifiers for the values stored in a dictionary.
Ex:
my_dict = {'name': 'Arun', 'age': 25, 'city': 'Mysuru’} if you print individual
for k in my_dict.keys(): print(my_dict["name"])
print(k)
values():
• The values() method allows you to access the values of a dictionary.
• Values are the actual data stored in the dictionary, associated with their respective keys.
Ex:
my_dict = {'name': 'Arun', 'age': 25, 'city': 'Mysuru’}
8
for v in my_dict.keys():
print(v)
items(): The items() method allows you to access both the keys and values of a dictionary
together.
Ex:
my_dict = {'name': ‘Arun', 'age': 25, 'city’:’Mysuru’}
for key, value in my_dict.items():
print(key,value)
or
print('key: ' + str(key) + ', value: ' + str(value))
9
Checking Whether a Key or Value Exists in a
Dictionary
Ex:
my_dict = {'name': ‘Arun', 'age': 25, 'city’:’Mysuru’}
if 'name' in my_dict:
print("The key 'name' exists in the dictionary.")
else:
print("The key 'name' does not exist in the dictionary.")
The get() Method:
The get() method that allows you to retrieve the value associated with a specific key. It provides a
way to access dictionary elements while handling cases where the key might not exist in the dictionary.
Syntax: [Link](key, default)
NOTE: Here default is optional
Ex:
my_dict = {'name': ‘Arun', 'age': 25, 'city': ‘Mysuru’} 10
name = my_dict.get('name’)
print(name) # Output: Arun
occupation = my_dict.get('occupation’)
print(occupation) # Output: None
In this example, my_dict.get('name') retrieves the value associated with the key 'name', which is ‘Arun'. Since
the key exists in the dictionary, the corresponding value is returned. However, when my_dict.get('occupation')
is called, it returns None because the key 'occupation' is not present in the dictionary.
The setdefault() Method: The setdefault() method that allows you to retrieve the value associated with a
specific key. If the key does not exist in the dictionary, it also enables you to set a default value for that key.
Syntax: [Link](key, default)
Ex:
my_dict = {'name': ‘Arun', 'age': 25, 'city': ‘Mysuru’}
name = my_dict.setdefault('name’,’unknown’)
print(name) # Output: Arun
occupation = my_dict.setdeafult('occupation’,’unemployed’)
print(occupation) # Output: unemployed
11
Pretty Printing
• Pretty printing refers to formatting complex data structures, such as dictionaries or lists, in a
visually appealing and easy-to-read manner.
• In Python, the pprint module provides a pprint() function that allows you to achieve pretty
printing.
Ex:
import pprint
my_dict = {'name': ‘Arun', 'age': 25, 'city': ‘Mysuru’}
[Link](my_dict) // [Link](my_dict,width=30)
OUTPUT: {'name': ‘Arun', 'age': 25, 'city': ‘Mysuru’}
OUTPUT: {‘name’:’Arun,
‘age’:25,
‘city’:’Mysuru’}
12
Using Data Structures to Model Real-
World Things
A data structure is a storage that is used to store and
organize data. It is a way of arranging data on a computer
so that it can be accessed and updated efficiently.
This is where lists and dictionaries can come in. You can use them
to model real-world things, like chessboards
Ex: Chess_borad={‘a1’,’a2’,’a3’, etc}
In algebraic chess notation, the
spaces on the chessboard are
identified by a number and letter
coordinate
A tic-tac-toe board looks like a large hash symbol (#) with nine slots 13
that can each contain an X, an O, or a blank. To represent the board
with a dictionary, you can assign each slot a string-value key
Thus, you’ll need to store nine strings. You can use a dictionary of values for
this. The string value with the key 'top-R' can represent the top-right corner, the
string value with the key 'low-L’ can represent the bottom-left corner, the string
value with the key 'mid-M' can represent the middle, and so on.
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ‘,
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ‘,
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
theBoard = {'top-L': ‘X ', 'top-M': ‘ O', 'top-R': ‘X ‘,
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ‘,
'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
Partial code snippet for a Tic-Tac-Toe game
14
theBoard = {
'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'low-L': ' ', 'low-M': ' ', 'low-R': ' '
}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
printBoard(theBoard)
theBoard = {
'top-L': ' ', 'top-M': ' ', 'top-R': ' ', Write a program of Tic-tac -Toe
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 15
'low-L': ' ', 'low-M': ' ', 'low-R': ' '
}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on which space?')
move = input()
theBoard[move] = turn
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
16
Nested Dictionaries and Lists
Nested dictionaries and lists that allow you to store complex, hierarchical data. They can be used to represent and
organize data in a structured manner.
# Nested Dictionary Example 'Emily': {
'age': 22,
student data = { 'major': 'Physics',
'John': { 'grades': [78, 86, 80]
'age': 21, }
'major': 'Computer Science', }
'grades': [85, 90, 92]
}, # Accessing nested dictionary values
'Sarah': { print(student_data['John']['age']) # Output: 21
'age': 20, print(student_data['Sarah']['major']) # Output:
'major': 'Mathematics', Mathematics
'grades': [95, 88, 91] print(student_data['Emily']['grades'][0]) # Output: 78
},
# Nested List Example 17
fruits = [
['Apple', 'Banana', 'Cherry'],
['Grape', 'Kiwi', 'Mango'],
['Orange', 'Pineapple', 'Strawberry']
]
# Accessing nested list values
print(fruits[0][1]) # Output: Banana
print(fruits[2][2]) # Output: Strawberry
print(fruits[1]) # Output: ['Grape', 'Kiwi', 'Mango']
Important Questions:
18
[Link] is list? Explain the concept of slicing and indexing with proper examples.
[Link] are the different methods supports in python List. Illustrate all the methods with an example.
[Link] is dictionary? Illustrate with an example python program the usage of nested dictionary.
[Link] with a programming example to each:
(ii) get()
(iii) setdefault()
5. Develop suitable Python programs with nested lists to explain [Link]( ) and [Link]( ) methods
[Link] append() and index() functions with respect to lists in Python.
[Link] are immutable. Explain with Python programming example.
[Link] different ways to delete an element from a list with suitable Python syntax and programming examples.
19
THANK YOU
“Life is short. Live it. fear
is natural. Face it. Memory
is powerfuL. use it.”