0% found this document useful (0 votes)
4 views53 pages

4_ DICTIONARIES_INTRODUCTION

The document covers the concepts of strings and dictionaries in Python, detailing their creation, accessing, modifying, and deleting items. It explains the differences between indexed and associative data structures, emphasizing the mutable nature of dictionaries and their key-value pair organization. Additionally, it includes methods for sorting dictionaries and retrieving keys, values, and items.

Uploaded by

gj88rd466g
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)
4 views53 pages

4_ DICTIONARIES_INTRODUCTION

The document covers the concepts of strings and dictionaries in Python, detailing their creation, accessing, modifying, and deleting items. It explains the differences between indexed and associative data structures, emphasizing the mutable nature of dictionaries and their key-value pair organization. Additionally, it includes methods for sorting dictionaries and retrieving keys, values, and items.

Uploaded by

gj88rd466g
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/ 53

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 1
• Python Standard Libraries
Associative data structure

• Elements of indexed linear data structures, such as


lists, are ordered —the first element (at index 0),
second element (at index 1), and so forth.
• In contrast, the elements of an associative data
structure are unordered, instead accessed by an
associated key value.
• In Python, an associative data structure is provided by
the dictionary type.
Indexed vs. Associative Data Structure
Average temperature for each day of a week :
Sunday – 68.8, Monday – 70.2,Tuesday – 67.2, Wednesday – 71.8 Thursday – 73.2
Friday – 75.6, Saturday – 74.0
Ordered Data Structure – List
daily_temp=[68.8,70.2,67.2,71.8,73.2,75.6,74.0]

Associative Data Structure – Dictionay


daily_temp = {'sun': 68.8, 'mon': 70.2, 'tue':
67.2, 'wed': 71.8,'thur': 73.2, 'fri': 75.6, 'sat':
74.0}

• The location that an element is stored in and retrieved from within an


associative data structure depends only on its key value, thus there is no
logical first element, second element, and so forth.
• The specific location that a value is stored is determined by a particular
method of converting key values into index values called hashing.
Hashing
• It is a technique to convert a range of key values into a range of
indexes of an array.
What Is a Dictionary?
• A dictionary is a mutable, associative data structure of variable
length.
• The syntax:
Dictionary_name={key1:value1, key2:value2,….keyn:valuen}

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

• In this case, the temperature for a specific date is retrieved by,


temps[('Apr', 14, 2001)] ➝ 74.6
Difference between List and Dictionary
• List is an ordered set of elements. But, a dictionary is a
data structure that is used for matching one element
(Key) with another (Value).
• In List, the index values can be used to access a
particular element. But, in dictionary key represents
index. Remember that, key may be a number or a
string.
• Lists are used to look up a value whereas a dictionary is
used to take one value and look up another value.
Points to remember
 Dictionaries are Python’s implementation of a data structure,
generally known as associative arrays, hashes, or hashmaps.
 We can think of a dictionary as a set of key:value pairs; where
each key is mapped to a single value.
 The important properties of Python dictionaries are as follows:
 Dictionaries are unordered – Items stored in a dictionary aren’t kept in
any particular order.
 Dictionaries are changeable (mutable) – They can be changed in place,
can grow and shrink on demand.
 Accessed by keys – Dictionary items are accessed by keys, not by their
position (index).
 Dictionaries can be nested – A dictionary can contain another
dictionary (Nested Dictionary).
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 10
• Python Standard Libraries
How to create a dictionary?
• Place items inside curly braces {} separated by
comma
• Each item is key value pair
• Each key is separated from its associated value by a
colon :
• Values can be of any data type and can repeat
• keys must be of immutable type and must be unique.
• Example:
stu = {'name': 'Balu', 'age': 19, 'dept': 'English'}
Dictionary Creation Cont’d
• Keys must be unique:
– If we specify a key more than once during the
creation of a dictionary, the last value for that key
becomes
Example: the associated value.

Output:

•Notice that the first occurrence of ‘name’ is replaced by the


second one.
Dictionary Creation Cont’d

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'}

Example 3: [ lowercase and uppercase of consonants in the given string]


str="welcome"
D={ch.lower():ch.upper() for ch in str if ch not in "aeiou"}
print(D)
Output3:
{'w': 'W', 'l': 'L', 'c': 'C', 'm': 'M'}
Use dict() function along with the zip()
function
zip() Function
zip([iterables])
• Combines items from each of the specified iterables.
• It returns an iterator that can generate tuples
• In the tuple the items of each passed iterable at same index are
paired together.
Example:

Output:
Few More Examples
Output:

Iterables with Different Length:


- The iterable with least items decides the length of the
resulting iterable.

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

Sort a dictionary contents by key

Sort dictionary contents by Value


Get All Keys, Values and Key: Value Pairs
• Three dictionary methods,
 keys() - return all of the dictionary’s keys
 values()- return all of the dictionary’s values
 items()- return all of the dictionary’s and key-value pairs
• All the three methods return iterable object
• These methods are useful in loops that need to
step through dictionary entries one by one.
• If we want a true list from these methods, wrap
them in a list() function.
Get All Keys, Values and Key: Value Pairs Cont’d
Dictionary Sorting Cont’d
Sort Dictionary contents by keys using dict.keys():
 dict.keys() returns a iterable view of all the keys in dictionary.
 We can create a new sorted dictionary from this iterable
sequence of keys using sorted(dict.keys())
Dictionary Sorting Cont’d
Sort Dictionary contents by keys using dict.items():
dict.items() returns an iterable sequence of tuples
that contains all key value pairs in dictionary.
We can create a new sorted list of tuple by this
iterable sequence sorted(dict.items())
By default sorted will sort the list of tuple by 1st
element in tuple i.e. on 0th index.
So list of tuples (key / value pairs) is sorted by keys.
It’s more efficient than previous method in terms of
complexity, because after sorting the iterable
sequence we don’t need to search for value for key
like in case of dict.keys().
Dictionary Sorting Cont’d

• We can achieve the same using List Comprehension,


Sorting dictionary contents in reverse order
of keys
• Both the previous solutions sorted the dictionary by key but in
ascending order
• If we want to sort the contents by descending order of keys, then pass
an attribute reverse=True in sorted() function
sorted(iterable_sequence, reverse=True)

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:

•We can do the same using List comprehension too,


Sorting dictionary by value in reverse Order

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

You might also like