0% found this document useful (0 votes)
0 views

Dictionary Notes

The document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It explains the differences between ordered and unordered collections, highlighting the mutable nature of dictionaries and their key-value pair structure. Additionally, it covers methods for creating, accessing, updating, and removing items from dictionaries, along with examples for better understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Dictionary Notes

The document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It explains the differences between ordered and unordered collections, highlighting the mutable nature of dictionaries and their key-value pair structure. Additionally, it covers methods for creating, accessing, updating, and removing items from dictionaries, along with examples for better understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

DATA STRUCTURE:

Data structure are the structures that hold and organize data or information.
The four main types are lists, tuples, sets and dictionaries.

SEQUENCE DATA TYPE ALLOWS YOU TO


ORGANISE AND STORE MULTIPLE VALUES
EFFICIENTLY.
Ordered Collection in Python:

Ordered collection/sequence refers to the arrangement of elements in the same order


as they are specified initially.

So Strings, Lists, Tuples are ordered collections of objects. And these data structures
maintain in order.

Unordered Collection in Python:

An unordered collection/sequence refers to the arrangement of elements in the


different order as they are specified initially.

For example, in set and dictionaries, initial order – the order in which we specified the
elements is not maintained. So Sets and Dictionary are unordered collections of
objects.
An unordered collection/sequence called Dictionary.

Unlike sequence, python collection do not have any order. They are unordered and
unindexed data structures. This means that is not necessary to get the order in which
we insert items.

Python Sequences:

 Each sequence contains a finite number of elements.


 The elements are arranged in some order in the sequence.
 It is possible to iterate over the elements in the sequence, according to their order.
 It is also possible to check if an element is in sequence or not.
Dictionary in Python:

The main purpose of a dictionary is to map unique keys with a value so that retrieving
information is optimized when we know the key.

Dictionaries are mutable and we can simply add a new key-value pair in the dictionary
by assigning them.

Example: Telephone Directory – numbers are stored according their name and
address.
So here,

Name - key
Telephone numbers - value
Dictionary in Python:

Python dictionary is an unordered collection of items where each item is


key-value pair. We can also refer to the dictionary as a mapping
between a set of keys/indices and set of values.

{“Python”:”dictionary”}

Dictionary is an unordered collection of items


where each item consist of key and a value.

It is a mutable (can modify its content. But key


must be unique and immutable.
Importance features of Dictionaries:

1. Each key maps to a value. The association of a key and a values is called
a “key-value pair”. There is no defined order for the pairs; thus a
dictionaries are unordered.

2. Each key is separated from its value by a colon (:) and entire dictionary is
closed in curly braces { } example: {“Python” : “Dictionary”}

3. Keys are unique and immutable; Values are mutable and can be changed.

4. The elements in a dictionary are indexed by keys and not numbers.


Importance features of Dictionaries:

5. The values of a dictionary can be of any type, but the keys must be of
immutable data type such as string, numbers or tuples.

d1={1:'one', 'two':2, (1,2,3): 'Numbers', 1.5: 'Float'}

4. Dictionary is mutable. We can be add new items and change the values of
existing items.
KEYS VALUES

1 ONE

2 TWO

3 THREE
CREATING A DICTIONARY:

It is enclosed in curly braces { } and each item is separated from other item by
a comma (,).

Within each item, key and values are separated by a colon (:).

Syntax:

<dictionary_name>={‘key1’: ‘value1’, ‘key2’: ‘value2’


‘key3’: ‘value3’,….. ‘keyn’: ‘valuen’}

Dictionary is an extremely useful data storage construct for storing and


retrieving all key-value pairs, where each element is accessed by a unique key.
INITIALIZING A DICTIONARY:

Passing a value in dictionary at declaration is Dictionary Initialization.

Examples:
KEYS

d= { } #empty dictionary

mydic={'R':'Rainy', 'S':'Summer', 'W':'Winter', 'A':'Autumn'}


print(mydic)

Output: VALUES

{'R': 'Rainy', 'S': 'Summer', 'W': 'Winter', 'A': 'Autumn'}


Example 2:

d1={1:'one',2:'two',3:'three',4:'four'}
d2={1:10,2:20,3:30,4:40,5:50}
d3={1:'one', 'two':2, (1,2,3): 'Numbers', 1.5: 'Float'}
print(d1)
print(d2) Note: Dictionary keys are case-sensitive.
print(d3) i.e. same name but different cases of
key will be treated distinctly.

Output

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}


{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
{1: 'one', 'two': 2, (1, 2, 3): 'Numbers', 1.5: 'Float'}
METHODS TO CREATE A DICTIONARY:
To create a dictionary, key-value pairs are separated by a comma and are enclosed
in two curly braces { }. In key-value pair, each key is separated from its value by a
colon (:)
1. To create an empty dictionary by assigning two curly braces to a variable name.
Output:
d1={ }
print(type(d1)) <class 'dict'>

2. To create a dictionary using string data type for both key-value pairs.

d2={'input':'Keyboard','output':'Printer','language':'Python'}
print(d2) Output:

{'input': 'Keyboard', 'output': 'Printer', 'language': 'Python'}


{}

METHODS TO CREATE A DICTIONARY:


3. To create a dictionary with built-in function dict( ). This function is used to create a
new dictionary with no items.

d3=dict() Output:
print(d3) {} Represent an empty dictionary

dict( ) function can also be used to create a copy of dictionary by passing a dictionary
as an argument to dict () function.

a={1:'one',2:'two'} Output:
b=dict(a) {1: 'one', 2: 'two'}
print(b)
{}

ADDING AN ITEM TO THE DICTIONARY:


To add an item to the dictionary, we can use square brackets [ ] for initializing
dictionary values along with the key.

d=dict()
print(d)
d[1]="one“
d[2]="two“
d[3]="three“
d[4]="four“
d[5]="five“
print(d) Output:

{}
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
{}

ACCESSING ELEMENTS IN A DICTIONARY:


To access dictionary elements, you can the familiar square brackets [ ] along with the
key to obtain its value. One value at a time can be accessed from dictionary by
defining the key.

Syntax:

<dictionary_name>[key]

Example: Output:

dict1={'name':'Riya','age':7,'class':'first'} dict1['Name']: Riya

print("dict1['Name']:", dict1['name'])
{}

TRAVERSING A DICTIONARY:
Traversing a dictionary means accessing each element of a dictionary. This can be
done by using a for loop or a while loop for iterating the dictionary elements.

in operator using for loop:

d={1:'one',2:'two',3:"three",4:"four",5:'five'}
for i in d:
print(i, ":", d[i])
Output:

1 : one
2 : two
3 : three
4 : four
5 : five
{}

TRAVERSING A DICTIONARY:
Write a program to enter names of employees and their salaries as input and store
them in a dictionary. (Using for loop)

num=int(input("Enter the number of employees: "))


count=1
employee = dict() #create an empty dictionary
for count in range (num) :
name=input ("Enter the name of the employees: ")
salary=int(input ("Enter the salary: "))
employee[name]=salary
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
{}

Output:

Enter the number of employees:


3
Enter the name of the employees:
Alka
Enter the salary:
12000
Enter the name of the employees:
Rajat
Enter the salary:
15000
Enter the name of the employees:
Yashu
Enter the salary:
10000

EMPLOYEE_NAME SALARY
Alka 12000
Rajat 15000
Yashu 10000
{}

TRAVERSING A DICTIONARY:
classxi=dict()
n=int(input("Enter total number of sections in xi class: "))
i=1
while i<=n:
a=input("Enter sections:")
b=input("Enter stream name:")
classxi[a]=b
i=i+1
print("class",'\t',"stream name")
for i in classxi:
print("XI",'\t',i,'\t',classxi[i])
{}

Enter sections:
C
OUTPUT:
Enter stream name:
SCIENCE WITH CS
Enter total number of sections in xi class: Enter sections:
5 D
Enter sections: Enter stream name:
A COMMERCE WITH MATHS
Enter stream name: Enter sections:
SCIENCE WITH ECO E
Enter stream name:
Enter sections:
COMMERCE WITH IP
B
class stream name
Enter stream name: XI A SCIENCE WITH ECO
SCIENCE WITH BIO XI B SCIENCE WITH BIO
XI C SCIENCE WITH CS
XI D COMMERCE WITH MATHS
XI E COMMERCE WITH IP
{}

APPENDING VALUES A DICTIONARY:

We can add new elements to the existing dictionary, extend it with single pair of
values or join dictionaries into one.

If we want to add only one element to the existing dictionary, the new key-value pair
will be added at the end of the dictionary.

Syntax:

Dictionary_name[key]=value
{}

APPENDING VALUES A DICTIONARY:

Example:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday'}
print(d1)
d1['thur']='Thursday' #append new item
print(d1)
Output:

{'mon': 'Monday', 'tues': 'Tuesday', 'wed': 'Wednesday'}


{'mon': 'Monday', 'tues': 'Tuesday', 'wed': 'Wednesday', 'thur': 'Thursday'}
{}

UPDATING ELEMENTS A DICTIONARY:


We can also update a dictionary by modifying existing key-value pair by merging
another dictionary with an existing one.

Syntax:

<dictionary_name>[<key>]=<value>

Example:

d1={'Teena':18,'Riya':12,'Alya':22,'Ravi':25}
print(d1)
Output:
d1['Riya']=28
print(d1) {'Teena': 18, 'Riya': 12, 'Alya': 22, 'Ravi': 25}
d1['Priya']=20 {'Teena': 18, 'Riya': 28, 'Alya': 22, 'Ravi': 25}
print(d1) {'Teena': 18, 'Riya': 28, 'Alya': 22, 'Ravi': 25, 'Priya': 20}
{}

UPDATING ELEMENTS A DICTIONARY:

Note: While adding a value, if the key value already exists, the value gets updated.
Otherwise, a new key with the value is added at the end of the dictionary.

Update( ) function:

Two dictionaries can be merged into one by using update( ) method. It merges the keys
and values of one dictionary with another and overwrites values of the same key.

Syntax:

dictname.update(dictname2)
{}

UPDATING ELEMENTS A DICTIONARY:


Example:
Output:
d1={1:10,2:20,3:30} {1: 10, 2: 20, 3: 30}
d2={4:40,5:50} {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
print(d1)
d1.update(d2)
print(d1)

Example:

d1={1:10,2:30,3:30,4:40,5:50} Output:
d2={2:20,3:30,6:50} {1: 10, 2: 30, 3: 30, 4: 40, 5: 50}
print(d1) {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 50}
d1.update(d2)
print(d1)
{}

REMOVING AN ITEM FROM DICTIONARY:

We can remove an item from the existing dictionary by using del command or using
pop ( ) function.

1. Using del command:

The keyword ‘del’ is used to delete the key present in the dictionary. If the key to be
deleted is not found, then it raises an error.

del dictname[key]
{}

REMOVING AN ITEM FROM DICTIONARY:

Example:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thur':'Thursday'}
print(d1)
del d1['mon']
print(d1)

Output:

{'mon': 'Monday', 'tues': 'Tuesday', 'wed': 'Wednesday', 'thur': 'Thursday'}


{'tues': 'Tuesday', 'wed': 'Wednesday', 'thur': 'Thursday'}
{}

REMOVING AN ITEM FROM DICTIONARY:


Example:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thur':'Thursday'}
print(d1)
del d1['fri']
print(d1)
Output:

{'mon': 'Monday', 'tues': 'Tuesday', 'wed': 'Wednesday', 'thur': 'Thursday'}


Traceback (most recent call last):
File "main.py", line 3, in <module>
del d1['fri']
KeyError: 'fri'

Note: If a particular key is not there, then it will return result in KeyError
{}

REMOVING AN ITEM FROM DICTIONARY:


If you want to delete the entire dictionary, then give the dictionary name along with
del keyword without any key.

For example:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thur':'Thursday'}
del d1
print(d1) Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(d1)
NameError: name 'd1' is not defined

Note: the dictionary name d1 no longer exists in the memory.


{}

REMOVING AN ITEM FROM DICTIONARY:


2. using pop ( ) method:

Pop( ) method will not only delete the item specified by the key from the dictionary
but will also return the deleted value.

Syntax:
dictname.pop(key)
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday'}
d1.pop('wed')
'Wednesday'
print(d1)
{'mon': 'Monday', 'tues': 'Tuesday'}
{}

REMOVING AN ITEM FROM DICTIONARY:


3. using popitem ( ) method:

It returns and removes the last inserted (key, value) pair from the dictionary

Syntax:
dictname.popitem()

Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday','sat':'
Saturday'}
d1.popitem()
('sat', 'Saturday')
print(d1)
{'mon': 'Monday', 'tues': 'Tuesday', 'wed': 'Wednesday', 'thurs': 'Thursday', 'fri': 'Friday'}
{}

MEMBERSHIP OPERATOR: ‘in’ AND ‘not in’


The ‘in’ operator checks whether a particular key is there in the dictionary. It returns
True if specified key appears in the dictionary. Otherwise it returns False.

Example:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
'wed' in d1
True
'sun' in d1
False
'sun' not in d1
True
{}

COMMON DICTIONARY FUNCTIONS:


Python provides with number of ways to manipulate the dictionary.

len()

sorted(
clear() 1. len()
)
2. clear()
3. get()
popite
4. items()
get()
m() 5. keys()
Python 6. value()
Dictionary
Methods
7. copy()
8. from keys()
from
keys()
item() 9. popitem()
10. sorted()

copy() keys()

value()
{}

Python Dictionary Methods


1. len():

This method returns the length of key-value pairs in the given dictionary.

Syntax:

len(dictionary_name)

Example:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
len(d1)
6
{}

Python Dictionary Methods


2. clear():

It removes all items from the particular dictionary and returns an empty dictionary.

Syntax:
dictionary_name.clear()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.clear()
print(d1)
{}
{}

3. get(): Python Dictionary Methods

The get() method returns a value for the given key. If key is not available, then
returns the default value none.

Syntax:
dictionary_name.get(key, default=None)

Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.get('wed')
'Wednesday‘
print(d1.get('sun'))
None
{}

3. get(): Python Dictionary Methods

Example:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
print(d1.get('sun')) Note: Will return None as key does not exist
None

We can also specify our own message:

d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.get('sun','never')
'never'
{}

Python Dictionary Methods


4. items():

It returns the content of dictionary (dictionary items/key-value pairs) as a list of


tuples having pairs.

Syntax:
dictionary_name.items()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.items()
dict_items([('mon', 'Monday'), ('tues', 'Tuesday'), ('wed', 'Wednesday'), ('thurs',
'Thursday'), ('fri', 'Friday'), ('sat', 'Saturday')])
{}

Python Dictionary Methods


5. keys():

It returns a list of keys in a dictionary

Syntax:
dictionary_name.keys()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.keys()
dict_keys(['mon', 'tues', 'wed', 'thurs', 'fri', 'sat'])
{}

Python Dictionary Methods


6. values():

It returns a list of values from key-values pairs in a dictionary

Syntax:
dictionary_name.values()
Example:
d1={'mon':'Monday','tues':'Tuesday','wed':'Wednesday','thurs':'Thursday','fri':'Friday',
'sat':'Saturday'}
d1.values()
dict_values(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
{}

Python Dictionary Methods

6. copy():

We cannot copy a dictionary by using assignment (“=“) operator as it will create a


reference to the same dictionary variable and modifications done in any of the
dictionaries will be reflected in both dictionaries.

We can use built-in function copy() to create a new dictionary object by copying it
but it doesn’t modify the original dictionary

Syntax:

Newdic=olddic.copy()
{}

Python Dictionary Methods

Assigning a dictionary:

d1={'january':31,'February':28,'March':31}
d2=d1
print(d1)
print(d2)

Output:

{'january': 31, 'February': 28, 'March': 31}


{'january': 31, 'February': 28, 'March': 31}
{}

Python Dictionary Methods


Changes made to newdic are reflected to olddic:

d1={'january':31,'February':28,'March':31}
d2=d1
print(d1)
print(d2)
d2['April']=30
print(d2) Output:
print(d1) {'january': 31, 'February': 28, 'March': 31}
{'january': 31, 'February': 28, 'March': 31}
{'january': 31, 'February': 28, 'March': 31, 'April': 30}
{'january': 31, 'February': 28, 'March': 31, 'April': 30}
{}

Python Dictionary Methods


Copying a Dictionary:

d1={'january':31,'February':28,'March':31}
d2=d1
print("d1: ",d1) Output:
print("d2: ",d2)
d1: {'january': 31, 'February': 28, 'March': 31}
d3=d1.copy() d2: {'january': 31, 'February': 28, 'March': 31}
print("d3: ",d3) d3: {'january': 31, 'February': 28, 'March': 31}
d1: {'january': 26, 'February': 28, 'March': 31}
d2['january']=26 d2: {'january': 26, 'February': 28, 'March': 31}
print("d1: ",d1) d3: {'january': 31, 'February': 28, 'March': 31}
print("d2: ",d2)
print("d3: ",d3)
{}

Write a python program to input ‘n’ names and phone numbers to store it in a
dictionary and to input any name and to print the phone number of that particular
name.

d={}
n=int(input("Enter the Members Count: "))
for i in range(n):
name=str(input("Enter the Name: "))
phoneno=int(input("Enter the PhoneNo: "))
d[name]=phoneno
print(d)
n=input("Enter the name whose phoneno you want:")
print(n," Phone number is: ",d[n])
{}

Output:

Enter the Members Count:


3
Enter the Name:
aaa
Enter the PhoneNo:
12345
Enter the Name:
bbb
Enter the PhoneNo:
67865
Enter the Name:
ccc
Enter the PhoneNo:
98765
{'aaa': 12345, 'bbb': 67865, 'ccc': 98765}
Enter the name whose Phoneno u want:
bbb
bbb Phone number is: 67865
{}

Write a python program to find the number of occurrences of each character


present in the string inputted by user.

word=input("Enter any word")


d={}
for i in word:
Output:
d[i]=d.get(i,0)+1
for k,v in d.items(): Enter any word
print(k, "occurred", v, "times") hello
h occurred 1 times
e occurred 1 times
l occurred 2 times
o occurred 1 times
{}

Write a python program to find the number of occurrences of each vowel present in
the inputted string.

word=input("Enter any word") Output:


vowels = {'a','e','i','o','u'}
d={} Enter any word
pythonprogramming
for i in word: a occured 1 times
if i in vowels: i occured 1 times
d[i]=d.get(i,0)+1 o occured 2 times

for k,v in sorted(d.items()):


print(k, "occured", v, "times")
{}

Write a python program to find the 2 maximum values in a dictionary D with key-
value pairs as {'A':23,'B':56,'C':29,'D':42,'E':78}
The output should be displayed as:
Two maximum values are:
78
56
d={'A':23,'B':56,'C':29,'D':42,'E':78}
val=[] Output:
v=d.values() Two maximum values are:
for i in v: 78
val.append(i) 56
val.sort()
print(“Two maximum values are:")
print(val[-1])
print(val[-2])
Thank you

You might also like