Dictionary data type
Introduction to Dictionaries
Python dictionaries are dynamic data structures that hold key-value pairs which allow quick
and easy access to and modification of data
Define what dictionaries are in Python
Dictionary entries in Python are unordered sets of data that hold key-value pairs.
Dictionary keys can be any immutable type, including strings or integers, in comparison with
sequences like lists or tuples, which are indexed by a range of numbers
Curly braces {} are used to define dictionaries, and a colon (:) is used to separate each key-
value pair.
As an example:
Arranged a group of elements in the form of key value pair
Name: Kiran Malik Class Rollno
1. Creating Dictionaries
Explain how to create dictionaries using curly braces {} or the dict() constructor
In Python, dictionaries are powerful data structures that store key-value pairs. These key-value
pairs allow for efficient organization, retrieval, and manipulation of data. There are two main
methods for creating dictionaries:
using curly braces {} or the dict()
Curly Braces {} Method
The most common and concise way to create a dictionary is by using curly braces {}.
Inside the braces, you specify key-value pairs separated by colons:
Each key-value pair is separated by commas.
Keys can be of any immutable data type such as strings, numbers, or tuples (containing
immutable elements).
Values can be of any data type, including lists, tuples, dictionaries, or any other Python object.
Syntax
Dictname= { ‘fieldname’, value, fieldname ,value}
Example
dict = {“Roll No": 101, "Name": " Kiran Malik", "Class": "CSE" }
print(dict)
Output
{'Roll No': 101, 'Name': ' Kiran Malik', 'Class': 'CSE'}
Example
# Creating a dictionary of student names and their information
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print(dict)
output
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410, 'Marks': 890}
name,class,rollno,marks---------key
Kiran Malik, CSE,4410,890---------values
# Creating a dictionary with mixed data types
dict = {'Name': 'Kiran', 'age': 30, 'S': False}
# Creating a dictionary with tuples as keys
tdict = {(1, 2): 'tkey', ('a', 'b'): 'tupp'}
dict() Constructor Method
Another way to create a dictionary is by using the dict() constructor.
You can pass key-value pairs as arguments to dict(), either as keyword arguments or as iterable
sequences like lists or tuples of key-value pairs.
Example
# Creating a dictionary using keyword arguments
dict= dict(Manan=20, Rahul=22, kiyan=21)
# Creating a dictionary from a list of tuples
tuple_list = [('A', 20), ('B', 22), ('C', 21)]
student_ages = dict(tuple_list)
# Creating a dictionary from two lists
names = ['A', 'B', 'C']
ages = [20, 22, 21]
student_ages = dict(zip(names, ages))
print(student_ages)
# Creating a dictionary using keyword arguments
student_ages = dict(A=20, B=22, C=21)
# Creating a dictionary from a list of tuples
tuple_list = [('A', 20), ('B', 22), ('C', 21)]
student_ages = dict(tuple_list)
# Creating a dictionary from two lists
names = ['A', 'B', 'C']
ages = [20, 22, 21]
student_ages = dict(zip(names, ages))
Access elment
dict = {"Roll No": 101,"Name": " Kiran Malik","Class":"CSE"}
print(dict)
x = dict["Name"]
print(x)
Output
{'Roll No': 101, 'Name': ' Kiran Malik', 'Class': 'CSE'}
Kiran Malik
Change elements
dict = {"Roll No": 101,"Name": " Kiran Malik","Class":"CSE"}
dict["Class"] ="ECE"
print(dict)
Output
{'Roll No': 101, 'Name': ' Kiran Malik', 'Class': 'ECE'}
Print Keys
dict = {"Roll No": 101,"Name": " Kiran Malik","Class":"CSE"}
for x in dict:
print(x)
Output
Roll No
Name
Class
Print values
dict = {"Roll No": 101,"Name": "Kiran Malik","Class": “CSE”}
for x in dict:
print(dict[x]
Output
101
Kiran Malik
CSE
#Display Items
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print(dict)
print("\nDisplay Items")
for i in dict.items():
print(i)
Output
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410, 'Marks': 890}
Display Items
('name', ' Kiran Malik')
('class', 'CSE')
('rollno', 4410)
('Marks', 890)
Delete: Deletes a particular item.
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print("\nDisplay Items")
print(dict)
del dict["Marks"]
print("\nDisplay Items aftter Deletion ")
print(dict)
Output
Display Items
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410, 'Marks': 890}
Display Items aftter Deletion
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410}
Iterating over (key, value) pairs:
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print("\nDisplay Items")
print(dict)
print("\nDisplay Items aftter iteration ")
for key in dict:
print(key, dict[key])
Output
Display Items
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410, 'Marks': 890}
Display Items aftter iteration
name Kiran Malik
class CSE
rollno 4410
Marks 890
Example
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print("\nDisplay Items")
print(dict)
print("\nDisplay Items aftter iteration ")
for k,v in dict.items():
print(k,v)
Output
Display Items
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410, 'Marks': 890}
Display Items aftter iteration
name Kiran Malik
class CSE
rollno 4410
Marks 890
List of Dictionaries
dict= [{"name": " Kiran Malik"},{"class":"CSE"},{"rollno": 4410},{"Marks":890}]
print("\nDisplay Items")
print(dict)
Output
Display Items
[{'name': ' Kiran Malik'}, {'class': 'CSE'}, {'rollno': 4410}, {'Marks': 890}]
Modify the dictionary
dict= [{"name": " Kiran Malik"},{"class":"CSE"},{"rollno": 4410},{"Marks":890}]
print("\nDisplay Items")
print(dict)
dict[2]["city"]="Rohtak"
print("\nDisplay Items after modification")
print(dict)
Output
Display Items
[{'name': ' Kiran Malik'}, {'class': 'CSE'}, {'rollno': 4410}, {'Marks': 890}]
Display Items after modification
[{'name': ' Kiran Malik'}, {'class': 'CSE'}, {'rollno': 4410, 'city': 'Rohtak'}, {'Marks': 890}
Example
dict = { "Name": "Kiran", "Designation": "AP", "Year": [2022], "dict1": {"Pooja": "Player"}}
print(dict["Name"])
print(dict["Designation"])
print(dict["Year"])
print(dict)
print(dict['dict1']["Pooja"])
dict2 = {
"Name": "Abhinav Dahiya",
"College": "MRIEM",
"Semester": "1St"
}
print(dict2)
Output:
Kiran
AP
[2022]
{'Name': 'Kiran', 'Designation': 'AP', 'Year': [2022], 'dict1': {'Pooja': 'Player'}}
Player
{'Name': 'Abhinav Dahiya', 'College': 'MRIEM', 'Semester': '1St'}
Accessing and Modifying Dictionary Elements
Accessing and modifying dictionary elements are fundamental operations when working with
dictionaries in Python. Here's an explanation of how these operations work:
1. Accessing Dictionary Elements
To access a value in a dictionary, you use its corresponding key. Python allows you to access
dictionary values using square brackets [] along with the key inside. When you provide a key,
Python looks up the associated value in the dictionary.
Syntax
# Syntax for accessing dictionary elements
value = dictionary_name[key]
Example
# Define a dictionary of student ages
#display Keys
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print(dict)
print("\nDisplay Keys")
# Accessing values using keys
for item in dict.keys():
print(item)
Output
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410, 'Marks': 890}
Display Keys
name
class
rollno
Marks
# Accessing values using specific keys
print(student_ages['Bob']) # Output: 22
print(student_ages['Alice']) # Output: 20
If the specified key is not present in the dictionary, Python raises a KeyError. To avoid this,
you can use the get() method, which returns None if the key is not found, or you can provide a
default value to be returned instead.
Syntax
# Syntax for using get() method to access dictionary elements
value = dictionary_name.get(key)
Example
# Using get() method to access values
print(student_ages.get('Bob')) # Output: 22
print(student_ages.get('David')) # Output: None
print(student_ages.get('David', 'Key not found')) # Output: 'Key not found'
2. Modifying Dictionary Elements
Dictionaries in Python are mutable, meaning you can modify their elements after they have
been created. You can change the value associated with a key, add new key-value pairs, or
remove existing key-value pairs.
Syntax
# Syntax for modifying dictionary elements
dictionary_name[key] = new_value
Example
# Modifying values
student_ages['Alice'] = 21
print(student_ages) # Output: {'Alice': 21, 'Bob': 22, 'Charlie': 21}
# Adding new key-value pairs
student_ages['David'] = 23
print(student_ages) # Output: {'Alice': 21, 'Bob': 22, 'Charlie': 21, 'David': 23}
# Removing key-value pairs
del student_ages['Charlie']
print(student_ages) # Output: {'Alice': 21, 'Bob': 22, 'David': 23}
These operations are essential for manipulating dictionary data in Python programs. They allow
you to retrieve specific values based on keys and modify the contents of dictionaries
dynamically during program execution, enabling efficient data management and manipulation.
1. Modifying Key-Value Pairs
Modifying a key-value pair involves updating the value associated with a specific key in the
dictionary. This can be done simply by assigning a new value to the key.
Example:
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Modify the value associated with the key 'Alice'
student_ages['Alice'] = 21
2. Adding Key-Value Pairs
Adding a new key-value pair involves inserting a new key along with its corresponding value
into the dictionary.
Example
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Add a new key-value pair
student_ages['David'] = 23
1. Deleting Key-Value Pairs
Deleting a key-value pair involves removing a specific key and its associated value from the
dictionary. This can be done using the del statement or the pop() method.
Using del statement
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Delete a key-value pair
del student_ages['Charlie']
Using pop() method
The pop() method removes the specified key and returns its associated value. If the key is not
found, it raises a KeyError, unless a default value is provided.
Length: we use len() method to get the length of dictionary
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print(len(dict))
Output
4
#pop method
# Define a dictionary
dict= {"name": " Kiran Malik","class":"CSE","rollno": 4410,"Marks":890}
print(dict)
print("\nDisplay Items")
# Remove and return the value associated with the key 'class'
print(dict.pop("class"))
print(dict)
Output
{'name': ' Kiran Malik', 'class': 'CSE', 'rollno': 4410, 'Marks': 890}
Display Items
CSE
{'name': ' Kiran Malik', 'rollno': 4410, 'Marks': 890}
# Remove and return the value associated with the key 'Bob'
bob_age = student_ages.pop('Bob')
# Remove and return the value associated with the key 'David', with a default value
david_age = student_ages.pop('David', 'Key not found')
4. Methods like get(), pop(), and update()
get(key[, default])
Returns the value associated with the specified key. If the key is not found, it returns None by
default, or the provided default value.
Useful for safely accessing dictionary values without raising a KeyError.
pop(key[, default])
Removes the specified key and returns its associated value. If the key is not found, it returns
None by default, or the provided default value.
Allows for safe removal of key-value pairs while retrieving the value.
update(iterable)
Updates the dictionary with the key-value pairs from the specified iterable (another dictionary
or an iterable of key-value pairs).
Useful for merging dictionaries or adding multiple key-value pairs at once.
Example
# Using get() method
alice_age = student_ages.get('Alice’) # Returns 20
# Using pop() method
removed_value = student_ages.pop('Alice’) # Removes 'Alice': 20 and returns 20
# Using update() method
additional_info = {'Eve': 24, 'Frank': 25}
student_ages.update(additional_info) # Adds {'Eve': 24, 'Frank': 25} to student_ages
These methods provide convenient ways to manipulate dictionary data, allowing you to
modify, add, or delete key-value pairs efficiently while handling various scenarios gracefully.
Dictionary Methods
Dictionary methods in Python provide versatile functionalities. keys(), values(), and items()
retrieve keys, values, and key-value pairs respectively. get(key) retrieves a value safely.
pop(key) removes and returns a value. update(iterable) merges dictionaries or adds multiple
key-value pairs. These methods facilitate efficient dictionary manipulation.
1. keys()
The keys() method returns a view object that provides a dynamic, iterable representation of all
the keys present in the dictionary.
This view object allows you to access the keys directly or iterate over them using a loop.
It provides a convenient way to retrieve all the keys in the dictionary without needing to convert
them to a list explicitly.
The view object reflects changes made to the dictionary in real-time, ensuring that it stays
synchronized with any modifications to the dictionary's keys.
access key
dict[‘name’]
dict[‘class’]
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Retrieve keys using keys() method
keys_view = student_ages.keys()
# Access keys directly or iterate over them
print(keys_view) # Output: dict_keys(['Alice', 'Bob', 'Charlie'])
for key in keys_view:
print(key) # Output: Alice, Bob, Charlie
Example
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Retrieve values using values() method
values_view = student_ages.values()
# Access values directly or iterate over them
print(values_view) # Output: dict_values([20, 22, 21])
for value in values_view:
print(value) # Output: 20, 22, 21
2. values ()
The values () method returns a view object that provides a dynamic, iterable representation of
all the values present in the dictionary.
Similar to keys(), this view object allows you to access the values directly or iterate over them
using a loop.
It provides a convenient way to retrieve all the values in the dictionary without needing to
convert them to a list explicitly.
Like keys(), the view object returned by values() reflects changes made to the dictionary in
real-time.
Example
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Retrieve values using values() method
values_view = student_ages.values()
# Access values directly or iterate over them
print(values_view) # Output: dict_values([20, 22, 21])
for value in values_view:
print(value) # Output: 20, 22, 21
3. items()
The items() method returns a view object that provides a dynamic, iterable representation of
all the key-value pairs present in the dictionary.
Each key-value pair is represented as a tuple (key, value) in the view object.
Like keys() and values(), this view object allows you to access the key-value pairs directly or
iterate over them using a loop.
It provides a convenient way to retrieve all the key-value pairs in the dictionary without needing
to convert them to a list explicitly.
As with the other view objects, the view returned by items() reflects changes made to the
dictionary in real-time.
Example
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Retrieve key-value pairs using items() method
items_view = student_ages.items()
# Access key-value pairs directly or iterate over them
print(items_view) # Output: dict_items([('Alice', 20), ('Bob', 22), ('Charlie', 21)])
for key, value in items_view:
print(key, value) # Output: Alice 20, Bob 22, Charlie 21
In summary, keys(), values(), and items() are essential methods for accessing the keys, values,
and key-value pairs of a dictionary in Python. They provide dynamic views that allow for
efficient retrieval and iteration over dictionary contents, while also ensuring synchronization
with any modifications to the dictionary.
Dictionary Operations
Common operations like checking membership, iterating through dictionaries, and combining
dictionaries.
1. Checking Membership
Dictionaries allow efficient membership testing using the in and not in operators.
Checking if a key exists in a dictionary is a common operation, especially before accessing its
associated value to avoid KeyError.
Example
# Define a dictionary
student_ages = {'Alice': 20, 'Bob': 22, 'Charlie': 21}
# Checking membership
if 'Alice' in student_ages:
print('Alice is present in the dictionary.')
2. Iterating Through Dictionaries
Dictionaries can be iterated using loops to access keys, values, or key-value pairs.
Iterating through dictionaries allows processing of each key or value, performing operations
such as filtering, transformation, or aggregation.
Example
# Iterate through keys
for key in student_ages:
print(key)
# Iterate through values
for value in student_ages.values():
print(value)
# Iterate through key-value pairs
for key, value in student_ages.items():
print(key, value)
3. Combining Dictionaries
Dictionaries can be combined using the update () method or dictionary unpacking (**) to merge
key-value pairs from multiple dictionaries into one.
This operation is useful for consolidating data from different sources or updating existing
dictionaries with new information.
# Define two dictionaries
dict1 = {'Alice': 20, 'Bob': 22}
dict2 = {'Charlie': 21, 'David': 23}
# Combine dictionaries using update() method
dict1.update(dict2)
print(dict1) # Output: {'Alice': 20, 'Bob': 22, 'Charlie': 21, 'David': 23}
# Combine dictionaries using dictionary unpacking
combined_dict = {**dict1, **dict2}
print(combined_dict) # Output: {'Alice': 20, 'Bob': 22, 'Charlie': 21, 'David': 23}
Counting Occurrences: Dictionaries are often used to count the occurrences of elements in a
sequence by using elements as keys and their counts as values.
Mapping: Dictionaries can be used to create mappings between related pieces of information,
such as mapping student names to their ages or mapping words to their frequencies in a text.
Caching: Dictionaries are useful for caching results of expensive computations or database
queries to avoid redundant calculations or database accesses.
Example (Counting Occurrences)
# Counting occurrences of elements in a list
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 1]
occurrences = {}
for num in numbers:
occurrences[num] = occurrences.get(num, 0) + 1
print(occurrences) # Output: {1: 4, 2: 3, 3: 2}
Nested dictionaries
Nested dictionaries in Python refer to dictionaries that contain other dictionaries as their values.
This concept allows for hierarchical organization of data, where each level represents a
different aspect or category of information.
Nested Dictionaries
Nested dictionaries enable the representation of complex data structures in a hierarchical
manner. Each key-value pair in a nested dictionary can have a value that is itself a dictionary,
allowing for multi-dimensional data organization.
Nested dictionaries are useful for representing data with multiple levels of abstraction or nested
relationships, such as hierarchical data models, configuration settings, or nested attributes.
2. Creating and Working with Nested Dictionaries
Nested dictionaries can be created by assigning dictionary literals as values to keys within
another dictionary.
Accessing and modifying values in nested dictionaries involves chaining key accesses using
multiple square brackets.
Iterating through nested dictionaries requires nested loops to traverse each level of the
hierarchy.
Example
# Creating a nested dictionary representing student information
students = {
'Alice': {'age': 20, 'major': 'Computer Science', 'grades': {'Math': 90, 'Physics': 85}},
'Bob': {'age': 22, 'major': 'Engineering', 'grades': {'Math': 88, 'Physics': 82}},
'Charlie': {'age': 21, 'major': 'Mathematics', 'grades': {'Math': 95, 'Physics': 90}}
}
# Accessing values in nested dictionaries
print(students['Alice']['age']) # Output: 20
print(students['Bob']['major']) # Output: 'Engineering'
print(students['Charlie']['grades']['Math']) # Output: 95
# Modifying values in nested dictionaries
students['Alice']['grades']['Math'] = 92
print(students['Alice']['grades']['Math']) # Output: 92
Work with dictionaries of dictionaries in Python:
1. Creating a Dictionary of Dictionaries
# Define a dictionary of dictionaries representing student information
students = {
'Alice': {'age': 20, 'major': 'Computer Science', 'grades': {'Math': 90, 'Physics': 85}},
'Bob': {'age': 22, 'major': 'Engineering', 'grades': {'Math': 88, 'Physics': 82}},
'Charlie': {'age': 21, 'major': 'Mathematics', 'grades': {'Math': 95, 'Physics': 90}}
1. Accessing Values in Nested Dictionaries
# Accessing values in nested dictionaries
print(students['Alice']['age']) # Output: 20
print(students['Bob']['major']) # Output: 'Engineering'
print(students['Charlie']['grades']['Math']) # Output: 95
2. Modifying Values in Nested Dictionaries
# Modifying values in nested dictionaries
students['Alice']['grades']['Math'] = 92
print(students['Alice']['grades']['Math']) # Output: 92
Exercise
1. WAP to create dictionary and apply method
dict= {} #empty dictionary
dict["Roll no"]=101 #add key and value
dict["Name"]="Kiran malik"
dict["Branch"]="CSE"
dict["City"]="Rohtak"
dict["Marks"]=890
print("\nDisplay Items")
print(dict)
print("length of string")
print(len(dict))
dict["Branch"] ="ECE"
print(dict)
print("\nDisplay Items")
x = dict["Name"]
print(x)
print("\nDisplay Keys")
for item in dict.keys():
print(item)
for item in dict.items():
print(item)
print("\nDisplay Items")
for x in dict:
print(dict[x])
print("\nDisplay Items")
for x in dict:
print(x)
print(dict.pop("Branch"))
print(dict)
del dict["Marks"]
print("\nDisplay Items aftter Deletion ")
print(dict)
Output
Display Items
{'Roll no': 101, 'Name': 'Kiran malik', 'Branch': 'CSE', 'City': 'Rohtak', 'Marks': 890}
length of string
5
{'Roll no': 101, 'Name': 'Kiran malik', 'Branch': 'ECE', 'City': 'Rohtak', 'Marks': 890}
Display Items
Kiran malik
Display Keys
Roll no
Name
Branch
City
Marks
('Roll no', 101)
('Name', 'Kiran malik')
('Branch', 'ECE')
('City', 'Rohtak')
('Marks', 890)
Display Items
101
Kiran malik
ECE
Rohtak
890
Display Items
Roll no
Name
Branch
City
Marks
ECE
{'Roll no': 101, 'Name': 'Kiran malik', 'City': 'Rohtak', 'Marks': 890}
Display Items aftter Deletion
{'Roll no': 101, 'Name': 'Kiran malik', 'City': 'Rohtak'}
Example
dict = {
"Roll No": 101,
"Name": "Kiran",
"Class": “CSE”
Access elment
dict = {
"Roll No": 101,
"Name": "Kiran",
"Class": “CSE”
print(dict)
x = dict["Name"]
print(x)
Change elements
dict = {
"Roll No": 101,
"Name": "Kiran",
"Class": “CSE”
dict["Class"] = “ECE”
print(dict)
Print Keys
dict = {
"Roll No": 101,
"Name": "Kiran",
"Class": “CSE”
for x in dict:
print(x)
Print values
dict = {
"Roll No": 101,
"Name": "Kiran",
"Class": “CSE”