Reference Notes on Python Dicionary
What is a dictionary?
✔ A ditionary is a built-in data type(data structure) in python that stores data in key:value pairs.
(OR)
A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists and tuples, each item in a dictionary is
a key-value pair (consisting of a key and a value).
✔ It is also called mapping data type because it maps keys to values.
✔ Before Python 3.6 → Dictionaries were considered unordered. Python 3.7 and later → Dictionaries are ordered (they preserve
insertion order).
✔ A dictionary is a mutable data type but when it comes it keys and values seperately, keys must be immutable data
type(int,float,complex,bool,string,tuple and frozenset etc) and value can be mutable or immutable.
✔ Each key:vaue pair is treated as an element/value/item in the dictionary, elements are seperated by comma and enclosed with curly
braces { }.
✔ Dictionary keys must be unique( no duplicate are allowed)
Advantages of dictionaries
✔ Fast data lookup(searching).
✔ Clear Key–Value Meaning (Readable Code), dictionaries make code more meaningful. For example user profile data.
✔ Flexible data storage, very useful format to store data like student and employee etc.
✔ Easy to update, examples like changing password for a username and updating bank account balance etc.
✔ Prevent duplicate keys
Dictionary structure
✔ {key:value , key1:value1 , key2:value2, .........} (key and value seperated by colon(:) )
✔ A few examples of dictionaries are given below
✔ { } An emplty dictionary
✔ {‘a’ : 22 , ‘b’ : “hello” , (11,22) : [‘a’,’b’]}
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
Creating a dictionary
#taking keys and values directly in the curly braces
d={1:'hi','a':22}
type(d)
<class 'dict'>
d1={} # It is an empty dictionary
type(d1)
<class 'dict'>
# Using dict() constructor
#syntax: d2=dict{key=value,key1=value1,key2=value2, .....}
d2=dict(name="VZM", distance=55, name1="vskp", distance1=100)
type(d2)
<class 'dict'>
print(d2)
{'name': 'VZM', 'distance': 55, 'name1': 'vskp', 'distance1': 100}
#Using zip function
(The zip() function in Python is used to combine multiple iterables (like lists, tuples, or strings) into a single iterator of tuples, where each
tuple contains elements from the same position in each iterable.)
k=['key1','key2','key3']
v=['value1','value2','value3']
d=dict(zip(k,v))
print(d)
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
#Adding elements or updating the dictionary
#Sytax: dictionaryname[key]=keyrelatedvalue
d1['key1']='value1'
print(d1)
{'key1': 'value1'}
d1['key2']='value2'
print(d1)
{'key1': 'value1', 'key2': 'value2'}
#Accessing elements in the dictionary
d2={'name': 'VZM', 'distance': 55, 'name1': 'vskp', 'distance1': 100}
#syntax: dictionaryname[key], it will return the associated value
d2['name']
'VZM'
d2['distance1']
100
d2['hi']
#The above code will throw an error because we are trying to access the key which is not present in the dictionary
KeyError: 'hi'
#updating dictionary value
#syntax: dictionaryname[key]=valuetobechanged
d2={'name': 'VZM', 'distance': 55, 'name1': 'vskp', 'distance1': 100}
d2['distance']=45
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
d2['distance1']=-30
print(d2)
{'name': 'VZM', 'distance': 45, 'name1': 'vskp', 'distance1': -30}
# Adding new key value pair to the dictionary
d2={'name': 'VZM', 'distance': 45, 'name1': 'vskp', 'distance1': -30}
d2['newkey']='newvalue'
print(d2)
{'name': 'VZM', 'distance': 45, 'name1': 'vskp', 'distance1': -30, 'newkey': 'newvalue'}
#No duplicate keys are allowed
d2={'name': 'VZM', 'distance': 45, 'name1': 'vskp', 'distance1': -30}
d2['name']='sklm'
print(d2) #duplicate key is not allowed but values is updated
{'name': 'sklm', 'distance': 45, 'name1': 'vskp', 'distance1': -30}
d2['distance']=5.99
print(d2)
{'name': 'sklm', 'distance': 5.99, 'name1': 'vskp', 'distance1': -30}
#Accessing values by get() method
d3={11:'first',22:'second'}
#syntax: [Link](key), it will the return passed key associated value
[Link](11)
'first'
[Link](22)
'second'
d3={11:'first',22:'second'}
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
print([Link](33))
None # We have not specified any default value so output is None
#Returning the default value if key is not present
d3={11:'first',22:'second'}
[Link](44,'key is not present in the dictionary')
'key is not present in the dictionary'
[Link](33,0)
0
#in the dictionary 33 key is not present but we have set the default value is 0 so that is why it is returning 0
#Traversing/Accessing elements through loop
#syntax : for variable1,variable2 in [Link]():
print(variable1,variable2)
#Example code
d3={11: 'first', 22: 'second'}
for hi,hello in [Link]():
print(hi,hello)
11 first
22 second
#Another example code
for hi,hello in [Link]():
print(hello,hi)
first 11
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
second 22
The enumerate() function in Python is used to loop over something (like a list or tuple) and get both
• the index (position)
• the value (item) at the same time.
#A sample example
fruits=["apple","banana","mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 mango
The zip() function in Python is used to combine multiple iterables (like lists, tuples, or strings) into a single iterable of tuples. Each
tuple contains elements from the corresponding positions of the input iterables.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = zip(names, ages)
print(list(combined))
[('Alice', 25), ('Bob', 30), ('Charlie', 35)] #A list of tuple pairs
print(dict(zip(names,ages)))
{'Alice': 25, 'Bob': 30, 'Charlie': 35}
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
for n,a in zip(names,ages):
print(n,'age is',a)
Alice age is 25
Bob age is 30
Charlie age is 35
#Creating a dictionary by comprehension
(In Python, comprehensions are a short and clean way to create collections (list, tuple, dictionary, set) using a single line of code, usually with a
loop and optional condition.)
# We will create a dictionary where number is the key and its square as value
d4={x:x**2 for x in range(1,6)}
print(d4)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Removing elements from a dictionary by using pop() method
# Removing based on index(pop method)
d4={1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
#[Link](key), it will remove the key and its related value, and returns/displays value on screen
[Link](3)
9
print(d4)
{1: 1, 2: 4, 4: 16, 5: 25}
d4={1: 1, 2: 4, 4: 16, 5: 25}
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
[Link](4)
16
print(d4)
{1: 1, 2: 4, 5: 25}
#[Link]() will remove last item, and return/displays key, value pair on screen
d4={1: 1, 2: 4, 4: 16, 5: 25}
[Link]()
(5, 25)
print(d4)
{1: 1, 2: 4, 4: 16}
[Link]()
(4, 16)
print(d4)
{1: 1, 2: 4}
#clear method will clear all elements of that dictionary and only left with empty braces
d4={1: 1, 2: 4}
[Link]()
print(d4)
{}
# del will delete the dictionary
d4={}
del d4
print(d4)
Traceback (most recent call last):
File "/usr/lib/python3.12/idlelib/[Link]", line 580, in runcode
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
exec(code, [Link])
File "<pyshell#81>", line 1, in <module>
NameError: name 'd4' is not defined. Did you mean: 'd'?
#Membership operator
# It will return True or False, it works for keys only
d2={'name': 'VZM', 'distance': 55, 'name1': 'vskp', 'distance1': 100}
'name' in d2
True
'name1' not in d2
False
100 in d2
False
'vskp' in d2
False
Basic built-in function in dictionary
d1={11:'one',33:'three',22:'two'}
d2={'a':'first','c':'third','b':'second'}
d3={'b':'second',11:'one'}
print(len(d1),len(d2),len(d3))
332
print(min(d1),max(d1))
11 33
print(max(d2),max(d2))
cc
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
print(min(d3),max(d3))
TypeError: '<' not supported between instances of 'int' and 'str'
print(sum(d1))
66
print(sorted(d1))
[11, 22, 33]
print(sorted(d2))
['a', 'b', 'c']
print(sum(d2))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
print(sorted(d3))
TypeError: '<' not supported between instances of 'int' and 'str'
print(d1+d2)
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
print(d1*2)
TypeError: unsupported operand type(s) for *: 'dict' and 'int'
Fromkeys() Method
The fromkeys() method in Python is used to create a new dictionary with specified keys and a common default value.
Syntax: [Link](keys, value)
Parameters:
• keys → a sequence of keys (list, tuple, set, etc.)
• value (optional) → the value assigned to all keys
• Default value is None
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
keys = ["name", "age", "city"]
data = [Link](keys, "Unknown")
print(data)
{'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
Example Without Value
keys = ["a", "b", "c"]
data = [Link](keys)
print(data)
{'a': None, 'b': None, 'c': None}
Another Example
numbers = [1, 2, 3, 4]
result = [Link](numbers, 0)
print(result)
{1: 0, 2: 0, 3: 0, 4: 0}
The setdefault() method in Python dictionaries is used to get the value of a key.
If the key does not exist, it adds the key with a default value to the dictionary.
Syntax : [Link](key, default_value)
Example 1: Key Already Exists
student = {"name": "Rahul", "age": 20}
result = [Link]("name", "Anita")
print(result)
print(student)
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
Rahul
{'name': 'Rahul', 'age': 20} ("name" already exists ,So the value does not change)
Example 2: Key Does Not Exist
student = {"name": "Rahul", "age": 20}
result = [Link]("city", "Delhi")
print(result)
print(student)
Delhi
{'name': 'Rahul', 'age': 20, 'city': 'Delhi'} ("city" did not exist, Python added the key with value "Delhi")
Example 3: Without Default Value
data = {"a": 1, "b": 2}
[Link]("c")
print(data)
{'a': 1, 'b': 2, 'c': None}
The update() method in Python dictionaries is used to add new key–value pairs or modify existing
ones using another dictionary or iterable.
Syntax: [Link](other_dictionary)
Example 1: Updating Existing Values
student = {"name": "Rahul", "age": 20}
[Link]({"age": 25})
print(student)
{'name': 'Rahul', 'age': 25} (The value of "age" was updated from 20 to 25.)
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
Example 2: Adding New Key–Value Pair
student = {"name": "Rahul", "age": 20}
[Link]({"city": "Delhi"})
print(student)
{'name': 'Rahul', 'age': 20, 'city': 'Delhi'} (Since "city" did not exist, it was added.)
Example 3: Updating Multiple Values
student = {"name": "Rahul", "age": 20}
[Link]({"age": 25, "city": "Delhi", "course": "Python"})
print(student)
{'name': 'Rahul', 'age': 25, 'city': 'Delhi', 'course': 'Python'} ("age" updated, "city" and "course" added)
Example 4: Updating Using Another Dictionary
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 5, "c": 3}
[Link](dict2)
print(dict1)
{'a': 1, 'b': 5, 'c': 3} ("b" value changed, "c" added)
The all() function in Python is used to check if all elements in an iterable are True.
If every element is True, it returns True. If any element is False, it returns False.
When you pass a dictionary to all(), Python checks all the dictionary keys, not the values.
Returns True if all keys are truthy
• Returns False if any key is falsy (0, False, None, "", etc.)
• Values are ignored unless you explicitly check them.
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
Example 1: All keys are truthy
data = {1: "a", 2: "b", 3: "c"}
print(all(data))
True (#All keys (1, 2, 3) are non-zero → truthy → all() returns True.)
Example 2: Contains a falsy key
data = {0: "a", 1: "b"}
print(all(data))
False (# Key 0 is falsy → all() returns False.)
Example 3: Checking values instead of keys
data = {"a": 1, "b": 2, "c": 3}
print(all([Link]()))
True
Example4: if any value is falsy
data = {"a": 1, "b": 0, "c": 3}
print(all([Link]()))
False
The any() function in Python is the opposite of all(). When used with a dictionary, it primarily checks the keys, unless you
explicitly check the values or items.
Returns True if any key in the dictionary is truthy
• Returns False if all keys are falsy (0, False, None, "", etc.)
• Values are ignored unless accessed explicitly.
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT
Example 1: Any key is truthy
data = {0: "a", 1: "b", 2: "c"}
print(any(data))
True (# Keys are 0, 1, 2, 0 is falsy, but 1 and 2 are truthy → any() returns True)
Example 2: All keys are falsy
data = {0: "a", False: "b", None: "c"}
print(any(data))
False (#All keys are falsy → any() returns False)
(Similary we can check for values also)
Checking key–value pairs
data = {"a": 0, "b": 0}
print(any([Link]()))
True
([Link]() produces tuples [('a',0), ('b',0)]
• Tuples themselves are truthy in Python → any() returns True
Note: All non-empty tuples are considered True in Python, even if values inside are 0.
Prepared by [Link], Mentor in IT, dept of IT, RGU-SKLM
content source: Internet and ChatGPT