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

Python Data Structure-Dictionary PDF

The document provides information on dictionaries in Python. It discusses how to create, access, update, and delete elements from dictionaries. It also covers built-in dictionary functions like dict(), len(), get(), keys(), values(), items(), copy(), setdefault(), and update(). Examples are given to demonstrate adding elements to a dictionary from user input, finding the number of occurrences of letters/vowels in a string, and looking up student marks by name from a dictionary.

Uploaded by

Rajendra Buchade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Python Data Structure-Dictionary PDF

The document provides information on dictionaries in Python. It discusses how to create, access, update, and delete elements from dictionaries. It also covers built-in dictionary functions like dict(), len(), get(), keys(), values(), items(), copy(), setdefault(), and update(). Examples are given to demonstrate adding elements to a dictionary from user input, finding the number of occurrences of letters/vowels in a string, and looking up student marks by name from a dictionary.

Uploaded by

Rajendra Buchade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Learn

Complete
Python
In
Simple Way

1 https://www.youtube.com/durgasoftware
DICTIONARY
DATA STRUCTURE
STUDY MATERIAL

2 https://www.youtube.com/durgasoftware
֍ We can use List, Tuple and Set to represent a group of individual objects as a single
entity.
֍ If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.

Eg:
 rollno ---- name
 phone number -- address
 ipaddress --- domain name

֍ Duplicate keys are not allowed but values can be duplicated.


֍ Hetrogeneous objects are allowed for both key and values.
֍ Insertion order is not preserved
֍ Dictionaries are mutable
֍ Dictionaries are dynamic
֍ indexing and slicing concepts are not applicable

Note: In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it is
known as "Hash"

How to Create Dictionary?


 d = {} OR d = dict()
 We are creating empty dictionary. We can add entries as follows

1) d[100]="durga"
2) d[200]="ravi"
3) d[300]="shiva"
4) print(d)  {100: 'durga', 200: 'ravi', 300: 'shiva'}

 If we know data in advance then we can create dictionary as follows


 d = {100:'durga' ,200:'ravi', 300:'shiva'}
 d = {key:value, key:value}

How to Access Data from the Dictionary?


We can access data by using keys.

1) d = {100:'durga',200:'ravi', 300:'shiva'}
2) print(d[100]) #durga
3) print(d[300]) #shiva

If the specified key is not available then we will get KeyError


print(d[400])  KeyError: 400

3 https://www.youtube.com/durgasoftware
We can prevent this by checking whether key is already available or not by using
has_key() function or by using in operator.

d.has_key(400)  Returns 1 if key is available otherwise returns 0

But has_key() function is available only in Python 2 but not in Python 3. Hence
compulsory we have to use in operator.

if 400 in d:
print(d[400])

Q) Write a Program to Enter Name and Percentage Marks


in a Dictionary and Display Information on the Screen
1) rec={}
2) n=int(input("Enter number of students: "))
3) i=1
4) while i <=n:
5) name=input("Enter Student Name: ")
6) marks=input("Enter % of Marks of Student: ")
7) rec[name]=marks
8) i=i+1
9) print("Name of Student","\t","% of marks")
10) for x in rec:
11) print("\t",x,"\t\t",rec[x])

D:\Python_classes>py test.py
Enter number of students: 3
Enter Student Name: durga
Enter % of Marks of Student: 60%
Enter Student Name: ravi
Enter % of Marks of Student: 70%
Enter Student Name: shiva
Enter % of Marks of Student: 80%

Name of Student % of marks


--------------- ------------
durga 60%
ravi 70 %
shiva 80%

4 https://www.youtube.com/durgasoftware
How to Update Dictionaries?
֍ d[key] = value
֍ If the key is not available then a new entry will be added to the dictionary with the
specified key-value pair
֍ If the key is already available then old value will be replaced with new value.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) d[400]="pavan"
4) print(d)
5) d[100]="sunny"
6) print(d)

Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
{100: 'sunny', 200: 'ravi', 300: 'shiva', 400: 'pavan'}

How to Delete Elements from Dictionary?


1) del d[key]
 It deletes entry associated with the specified key.
 If the key is not available then we will get KeyError.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) del d[100]
4) print(d)
5) del d[400]

Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{200: 'ravi', 300: 'shiva'}
KeyError: 400

2) d.clear()
To remove all entries from the dictionary.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) d.clear()
4) print(d)

5 https://www.youtube.com/durgasoftware
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{}

3) del d
To delete total dictionary.Now we cannot access d.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) del d
4) print(d)

Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
NameError: name 'd' is not defined

Important Functions of Dictionary:


1) dict():
To create a dictionary

 d = dict()  It creates empty dictionary


 d = dict({100:"durga",200:"ravi"})  It creates dictionary with specified elements
 d = dict([(100,"durga"),(200,"shiva"),(300,"ravi")])
 It creates dictionary with the given list of tuple elements

2) len()
Returns the number of items in the dictionary.

3) clear():
To remove all elements from the dictionary.

4) get():
To get the value associated with the key

d.get(key)
If the key is available then returns the corresponding value otherwise returns None.It
wont raise any error.

6 https://www.youtube.com/durgasoftware
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d[100])  durga
3) print(d[400])  KeyError:400
4) print(d.get(100))  durga
5) print(d.get(400))  None
6) print(d.get(100,"Guest"))  durga
7) print(d.get(400,"Guest"))  Guest

5) pop():
d.pop(key)
 It removes the entry associated with the specified key and returns the
corresponding value.
 If the specified key is not available then we will get KeyError.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.pop(100))
3) print(d)
4) print(d.pop(400))

Output
durga
{200: 'ravi', 300: 'shiva'}
KeyError: 400

6) popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) print(d.popitem())
4) print(d)

Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
(300, 'shiva')
{100: 'durga', 200: 'ravi'}
If the dictionary is empty then we will get KeyError
d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'

7 https://www.youtube.com/durgasoftware
7) keys():
It returns all keys associated eith dictionary.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.keys())
3) for k in d.keys():
4) print(k)

Output
dict_keys([100, 200, 300])
100
200
300

8) values():
It returns all values associated with the dictionary.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.values())
3) for v in d.values():
4) print(v)

Output
dict_values(['durga', 'ravi', 'shiva'])
durga
ravi
shiva

9) items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]

1) d={100:"durga",200:"ravi",300:"shiva"}
2) for k,v in d.items():
3) print(k,"--",v)

Output
100 -- durga
200 -- ravi
300 -- shiva

8 https://www.youtube.com/durgasoftware
10) copy():
To create exactly duplicate dictionary (cloned copy)
d1 = d.copy();

11) setdefault():
d.setdefault(k,v)
 If the key is already available then this function returns the corresponding value.
 If the key is not available then the specified key-value will be added as new item to
the dictionary.

1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.setdefault(400,"pavan"))
3) print(d)
4) print(d.setdefault(100,"sachin"))
5) print(d)

Output
pavan
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
durga
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}

12) update():
d.update(x)
All items present in the dictionary x will be added to dictionary d

Q) Write a Program to take Dictionary from the Keyboard


and print the Sum of Values?
1) d=eval(input("Enter dictionary:"))
2) s=sum(d.values())
3) print("Sum= ",s)

Output
D:\Python_classes>py test.py
Enter dictionary:{'A':100,'B':200,'C':300}
Sum= 600

9 https://www.youtube.com/durgasoftware
Q) Write a Program to find Number of Occurrences of each Letter
present in the given String?
1) word=input("Enter any word: ")
2) d={}
3) for x in word:
4) d[x]=d.get(x,0)+1
5) for k,v in d.items():
6) print(k,"occurred ",v," times")

Output
D:\Python_classes>py test.py
Enter any word: mississippi
m occurred 1 times
i occurred 4 times
s occurred 4 times
p occurred 2 times

Q) Write a Program to find Number of Occurrences of each Vowel


present in the given String?
1) word=input("Enter any word: ")
2) vowels={'a','e','i','o','u'}
3) d={}
4) for x in word:
5) if x in vowels:
6) d[x]=d.get(x,0)+1
7) for k,v in sorted(d.items()):
8) print(k,"occurred ",v," times")

Output
D:\Python_classes>py test.py
Enter any word: doganimaldoganimal
a occurred 4 times
i occurred 2 times
o occurred 2 times

10 https://www.youtube.com/durgasoftware
Q) Write a Program to accept Student Name and Marks from the
Keyboard and creates a Dictionary. Also display Student Marks
by taking Student Name as Input?
1) n=int(input("Enter the number of students: "))
2) d={}
3) for i in range(n):
4) name=input("Enter Student Name: ")
5) marks=input("Enter Student Marks: ")
6) d[name]=marks
7) while True:
8) name=input("Enter Student Name to get Marks: ")
9) marks=d.get(name,-1)
10) if marks== -1:
11) print("Student Not Found")
12) else:
13) print("The Marks of",name,"are",marks)
14) option=input("Do you want to find another student marks[Yes|No]")
15) if option=="No":
16) break
17) print("Thanks for using our application")

Output
D:\Python_classes>py test.py
Enter the number of students: 5

Enter Student Name: sunny


Enter Student Marks: 90

Enter Student Name: banny


Enter Student Marks: 80

Enter Student Name: chinny


Enter Student Marks: 70

Enter Student Name: pinny


Enter Student Marks: 60

Enter Student Name: vinny


Enter Student Marks: 50

Enter Student Name to get Marks: sunny


The Marks of sunny are 90

11 https://www.youtube.com/durgasoftware
Do you want to find another student marks[Yes|No]Yes

Enter Student Name to get Marks: durga


Student Not Found

Do you want to find another student marks[Yes|No]No


Thanks for using our application

Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.

1) squares={x:x*x for x in range(1,6)}


2) print(squares)
3) doubles={x:2*x for x in range(1,6)}
4) print(doubles)

Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

12 https://www.youtube.com/durgasoftware

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy