4_ DICTIONARIES_INTRODUCTION
4_ DICTIONARIES_INTRODUCTION
• Strings • Dictionary
Introduction Creating
Indexing Accessing
Traversing Adding Items
Concatenating Modifying
Appending Deleting
Multiplying Sorting
Formatting Looping
Slicing Nested Dictionaries
Comparing Built-in Dictionary
Iterating Function
Basic Built-In String Functions Finding Key and Value in a Dictionary
• Modules
Module Loading and Execution
• Packages
01/27/2025 1
• Python Standard Libraries
Associative data structure
• Example:
daily_temp = {'sun': 68.8, 'mon': 70.2, 'tue': 67.2, 'wed': 71.8,'thur':
73.2, 'fri': 75.6, 'sat': 74.0}
• Here, each temperature has associated with it a unique key value
('sun', 'mon', etc.).
• The syntax for accessing an element of a dictionary is the same as
for accessing elements of sequence types, except that a
key value is used within the square brackets instead of an index
value: daily_temps['sun'].
Dictionary Example
Output:
Dictionary Cont’d
• Although strings are often used as key values, any immutable type such
as integer, float, bool, tuple and frozenset may be used as well
Example:
Output:
Output:
Output:
Exception will be
raised when mutable
object is used as a
Output: key
Dictionary Creation Cont’d
• We can also create a dictionary using the built-in function dict()
• We can convert two-value sequences into a dictionary with
Python’s dict() constructor.
• The first item in each sequence is used as the key and the
second as the value.
Output:
Output:
Dictionary Creation Cont’d
• When the keys are simple strings:
It is easier to specify key:value pairs
using keyword arguments.
Output:
Examples
Other Ways to Create Dictionaries
Create empty dictionary and add new values
Dictionary comprehension
Use dict() function along with the zip() function
Create empty dictionary and add new
values
Example 1:
D={}
print(D)
for i in range(5):
D[i]=i*i
print(D)
Output:
{}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Create empty dictionary and add new
Example 2:
values
D={}
print(D)
for i in range(5):
val=input("Enter data:")
D[i]=val
Output:
print(D)
{}
Enter data:apple
Enter data:banana
Enter data:Guava
Enter data:pine apple
Enter data:orange
{0: 'apple', 1: 'banana', 2: 'Guava', 3: 'pine apple', 4: 'orange'}
Dictionary comprehension
• It is an elegant and concise way to create new
dictionary from an iterable in Python.
• Syntax:
Example
Create a dictionary of numbers & squares
Option 2:
Option 1
Output:
Option 3:
Output:
Output:
Few More Examples
Example 1: [only even number and its square from 0 to 5]
D={i:i**2 for i in range(5) if i%2==0}
print(D)
Output1:
{0: 0, 2: 4, 4: 16}
Example 2: [ alphabet and three times the alphabet in the given string]
D={i:i*3 for i in "hai"}
print(D)
Output2:
{'h': 'hhh', 'a': 'aaa', 'i': 'iii'}
Output:
Few More Examples
Output:
Output:
Create a dictionary with list of zipped
keys/values
• Example:
Output:
UNIT IV STRINGS, DICTIONARIES, MODULES
• Strings • Dictionary
Introduction Creating
Indexing Accessing
Traversing Adding Items
Concatenating Modifying
Appending Deleting
Multiplying Sorting
Formatting Looping
Slicing Nested Dictionaries
Comparing Built-in Dictionary
Iterating Function
Basic Built-In String Functions Finding Key and Value in a Dictionary
• Modules
Module Loading and Execution
• Packages
01/27/2025 26
• Python Standard Libraries
Dictionary Accessing
• List use index
• Dictionary use keys
• Key can be used either inside square brackets or
with the get() method
• get() method returns the value for key if key is
in the dictionary, else None
• if key not found
Key within [] raises KeyError
get() returns None instead of KeyError
Dictionary Accessing Cont’d
Output:
UNIT IV STRINGS, DICTIONARIES, MODULES
• Strings • Dictionary
Introduction Creating
Indexing Accessing
Traversing Adding Items
Concatenating Modifying
Appending Deleting
Multiplying Sorting
Formatting Looping
Slicing Nested Dictionaries
Comparing Built-in Dictionary
Iterating Function
Basic Built-In String Functions Finding Key and Value in a Dictionary
• Modules
Module Loading and Execution
• Packages
01/27/2025 29
• Python Standard Libraries
Dictionary Adding or modifying items
• Dictionary is mutable
• We can add new items or change the value of
existing items using assignment operator
If the key is already present,
value gets updated (modify)
else
a new key: value pair is added to the
dictionary.
Dictionary Adding or modifying items Cont’d
Output:
UNIT IV STRINGS, DICTIONARIES, MODULES
• Strings • Dictionary
Introduction Creating
Indexing Accessing
Traversing Adding Items
Concatenating Modifying
Appending Deleting
Multiplying Sorting
Formatting Looping
Slicing Nested Dictionaries
Comparing Built-in Dictionary
Iterating Function
Basic Built-In String Functions Finding Key and Value in a Dictionary
• Modules
Module Loading and Execution
• Packages
01/27/2025 32
• Python Standard Libraries
Deleting items from dictionary
• Different ways:
Remove an Item by Key
Remove Last Inserted Item
Remove all Items
Deleting items from dictionary Cont’d
Remove an Item by Key:
1. pop(key) -method removes the key and returns its value.
2. del -statement removes the key and value but no return
value
Deleting items from dictionary Cont’d
• Remove Last Inserted Item:
– popitem() removes and returns the last inserted item
– In versions before 3.7, this method would remove a
random item.
Output:
Deleting items from dictionary Cont’d
Remove all Items
– clear() delete all keys and values from a dictionary
– del also remove entire dictionary itself
Example:1
Example:2
UNIT IV STRINGS, DICTIONARIES, MODULES
• Strings • Dictionary
Introduction Creating
Indexing Accessing
Traversing Adding Items
Concatenating Modifying
Appending Deleting
Multiplying Sorting
Formatting Looping
Slicing Nested Dictionaries
Comparing Built-in Dictionary
Iterating Function
Basic Built-In String Functions Finding Key and Value in a Dictionary
• Modules
Module Loading and Execution
• Packages
01/27/2025 37
• Python Standard Libraries
Dictionary Sorting
• How to Sort a Dictionary? by key or Value ?
Dictionary is like a hash table that store the elements by
calculating hashes of keys and orders of elements in it can
not be predicted
Therefore, its also called unordered container and we
cannot sort the dictionary in place
But we can create a either create a list of tuples (key
value pairs) which is sorted or we can iterate over the
contents of dictionary in sorted order
Dictionary Sorting Cont’d
• Different ways to sort the contents of dictionary
Output:
Sort dictionary contents by key using
custom key functions
• We can also sort the contents of dictionary by custom logic
sorted(iterable_sequence, key= Function)
• sorted() function accepts a key function as an argument and calls it
on each element prior to make comparison with other elements.
Output:
Dictionary Sorting Cont’d
• Sort dictionary contents by Value :
– dict.values() returns a view object that displays a list of all
values
– This function can be used along with sorted to display only the
values in sorted order as shown below,
Output:
Dictionary Sorting Cont’d
• If we need both key and value in sorted order based upon
the values, we can use the same sorted() function and
pass a key function that will return the 1st index element
of tuple i.e. the value field from the key/value pair
Output:
Output:
UNIT IV STRINGS, DICTIONARIES, MODULES
• Strings • Dictionary
Introduction Creating
Indexing Accessing
Traversing Adding Items
Concatenating Modifying
Appending Deleting
Multiplying Sorting
Formatting Looping
Slicing Nested Dictionaries
Comparing Built-in Dictionary
Iterating Function
Basic Built-In String Functions Finding Key and Value in a Dictionary
• Modules
Module Loading and Execution
• Packages
01/27/2025 50
• Python Standard Libraries
Looping in Dictionary
• We have different ways to iterate over a dictionary,
• Iterate over the dictionary using for loop over keys |“for in
dictionary”
– By using for in dictionary, it loops through all the keys in dictionary,
and for each key value, we can select the value and print it
Looping in Dictionary Cont’d
• Iterate over dictionary to access only values using
dict.values()
Output:
Looping in Dictionary Cont’d
• Iterate over key value pairs of dictionary using dict.items()
– Dict.items() returns a iterable view object of all key value
elements in the dictionary