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

11.Dictionary Datatype

The document provides an overview of dictionaries in Python, explaining their structure, properties, and how to create, access, update, and delete elements. It highlights key features such as the prohibition of duplicate keys, the mutability of dictionaries, and various built-in functions like get, pop, and update. Additionally, it includes examples of dictionary comprehension and comparisons with other data structures like lists, tuples, and sets.

Uploaded by

19010c055
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

11.Dictionary Datatype

The document provides an overview of dictionaries in Python, explaining their structure, properties, and how to create, access, update, and delete elements. It highlights key features such as the prohibition of duplicate keys, the mutability of dictionaries, and various built-in functions like get, pop, and update. Additionally, it includes examples of dictionary comprehension and comparisons with other data structures like lists, tuples, and sets.

Uploaded by

19010c055
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Dictionary:

 We 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.
Ex:
rollno name
username password
mobileno network

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


 Heterogeneous objects are allowed for both key and values.
 Insertion order is not preserved.
 It is mutable.
 Indexing and slicing are not applicable.
 Dictionaries can be created using pair of curly braces ( {} ). Each item in
the dictionary consist of key, followed by a colon, which is followed by
value. And each item is separated using comma (,)
 An item has a key and the corresponding value expressed as a pair, key:
value.

Creating dictionary:
Empty dict:
d={} #d=dict()
d[100]='gangadhar' d[103]='lokesh' d[104]='rajesh'
print(type(d))
print(d)

Accessing elements from dictionary:

We can access data by using keys.


Ex: d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d[103])
print(d[303])
If key is not found then it returns KeyError.

Ex:
# empty dictionary
my_dict = {}
print(my_dict)
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
friends = {'tom':'111-222-333','jerry':'666-33-111'}
print(friends)
print(friends['tom'])
print(friends.get('jerry'))
print(friends.get(1)) #none
print(friends['gangadhar']) #KeyError:

Ex:
month=int(input("Enter a number between 1 to 12"))
calender={1:'January',2:'February',3:'March',4:'April',5:'May',6:'June',7:'July',8:'
August',9:'September',10:'October',11:'November',12:'December'}
print("month %2d is: %2s"%(month,calender[month]))

Ex: Write a program to enter name and percentage of marks in a dictionary


and display information on the screen.
n=int(input("Enter number of students:"))
i=1
d={}
while i<=n:
name=input("Enter name:")
marks=int(input("Enter percentage of marks:"))
d[name]=marks
i=i+1
print("Name \t\t Marks")
for x in d:
print("{} \t\t {}".format(x,d[x]))

Update dictionary:
d[key]=value
 If key is available then only value will be replaced.
 If key is not available then new entry will be added.
Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
d[100]='lohit'
d[105]='ravi'
print(d)
How to delete elements from dictionary:
del d[key]
 If key is available then total entry will be deleted.
 If key is not available then we will get KeyError.
Ex: d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d)
del d[100]
print(d)
del d[105]
print(d)

To provide multiple values for key:


Ex:
l=[10,20,30]
d={100:l}
print(d)

Important functions in dictionary:


dict(): - To create empty dictionary.
- d=dict()  It creates a empty dictionary.
- d=dict({100:"gangadhar",103:"lokesh"}) It creates a dictionary with
specified elements.
- d=dict([(100,"gangadhar"),(103,"lokesh"),(104,"rajesh")]) It
creates dictionary with the given list of tuple elements.
len(): Returns the number of items in the dictionary.
clear(): - To remove all entries from the dictionary. del: - To remove
dictionary.

Ex: d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}


del d
print(d)

get(key): - It returns the value of the given key. If key is not found, it returns
None.
Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d.get(103))
print(d.get(101))
get(key,defaultvalue): - If the key is available then returns the corresponding
value otherwise returns default value.
Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
#print(d.get(100))
#print(d.get(110))
print(d.get(100,"Guest"))
print(d.get(110,"Guest"))

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.

Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d.pop(103))
print(d)
print(d.pop(130))

popitem(): - It removes an arbitrary item(key-value) from the dictionary and


returns it. If the dictionary is empty then we will get KeyError.
Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'} print(d) print(d.popitem())
print(d)

keys(): - It returns all keys associated with dictionary.


Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d.keys())
for k in d.keys():
print(k)

values(): - It returns all values associated with dictionary.


Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d.values())
for k in d.values():
print(k)
items(): It returns list of tuples representing key-value pairs.
[(k,v),(k,v)] Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d.items())
for k,v in d.items():
print(k,"—",v)

copy(): To create exactly duplicate dictionary.


Ex: d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d)
d1=d.copy()
print(d1)

setdefault(): 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.
Ex:
d={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
print(d.setdefault(113,"lohit"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)

update(): - It is used to add items of second dictionary to first dictionary.


Ex:
d1={100:'gangadhar', 103:'lokesh', 104:'rajesh'}
d2={'a':'apple','b':'banana'}
d1.update(d2)
print(d1)

Ex:
d1={1:"gangadhar",2:"lokesh",4:"rajesh",3:"lohit"}
print(d1.keys())
print(d1.values())
print(list(d1.keys()))
print(list(d1.values()))
print(tuple(d1.keys()))
print(tuple(d1.values()))
print(set(d1.keys()))
print(set(d1.values()))
print(sorted(d1.keys()))
print(sorted(d1.values()))

Ex:
d1={1:"gangadhar",2:"lokesh",4:"rajesh",3:"lohit"}
print(sorted(d1.keys()))
print(sorted(d1.values()))

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


for i in squares:
print(i)

for i in squares:
print(squares[i])

Ex:
in or not in operators
in and not in operators to check whether key exists in the dictionary.

my_disc={1:"gangadhar",2:"lokesh"}
#in not in
print(1 in my_disc)
print(2 not in my_disc)

Ex: d1={1:"gangadhar",2:"lokesh"}
d2={111:"gangadhar",222:"lokesh"}
d3=d1
print(id(d1))
print(id(d2))
print(id(d3))
print(d1 is d2)
print(d1 is d3)
print(d1 is not d2)
print(d1 is not d3)
print(d1==d2)
print(d1==d3)
print(d1!=d2)
print(d2!=d3)
print(1 in d1)
print(11 in d1)
print(1 not in d1)
print(11 not in d1)
Ex:
l1=[10,20,30,40]
l2=["gangadhar","lokesh","rajesh","lohit"]
x = zip(l1,l2)
d = dict(x)
print(d)

Ex:
d1={10:"gangadhar",20:"lokesh"}
d2={1:"aaa",2:"bbb"}
l1 = list(d1.keys())
l2 = list(d2.values())
x = zip(l1,l2)
d = dict(x)
print(d)

Ex:
Equality Tests in dictionary
== and != operators tells whether dictionary contains same items not.

d1={1:"gangadhar",2:"lokesh"}
d2={111:"gangadhar",222:"lokesh"}
d3=d1
print(id(d1))
print(id(d2))
print(id(d3))
print(d1==d2)
print(d1==d3)
print(d1!=d2)
print(d2!=d3)
d1={1:"gangadhar",2:"lokesh",3:"rajesh",4:"lohit"}
d2 = d1.copy()
d3=d1; print(d2)
print(d3)
print(list(d1.keys()))
print(tuple(d1.keys()))
print(list(d1.values()))
print(tuple(d1.values()))
print(d1.items())
#we could turn this into a list with two-tuples

Ex:
d1 = {1:"gangadhar",3:"lokesh"}
d2 = {2:"aaa",4:"bbb"}
x = {**d1,**d2}
print(x)

Ex:
keys = ["bird", "plant", "fish"]
# Create dictionary from keys.
d = dict.fromkeys(keys, 5)
# Display.
print(d)

Ex:
pairs = [("cat", "meow"), ("dog", "bark"), ("bird", "chirp")]
# Convert list to dictionary.
lookup = dict(pairs)
print(lookup)
print(lookup.items())

Ex: Write a program to take dictionary from the keyboard and print sum of
values.
d=eval(input("Enter dictionary:")) s=sum(d.values()) print("sum of values=",s)

Ex: Write a program to count number of occurrences of each letter present in


the given string. word=input("Enter some word:") d={} for x in word:
d[x]=d.get(x,0)+1
print(d) print(sorted(d))

Ex: Write a program to print number of occurrences of vowels present in the


given string.
word=input("Enter some word:")
vowels={'a', 'e', 'i', 'o', 'u'} d={} for x in word: if x in vowels:
d[x]=d.get(x,0)+1 print(d) print(sorted(d))
Ex: Write a program to accept name and % of marks from keyboard and creates
a dictionary. Also display student marks by taking student name as input.
n=int(input("Enter no of students:"))
d={}
for i in range(n):
name=input("Enter student name:")
marks=input("Enter marks:")
d[name]=marks

while True:
name=input("Enter student name to get marks:")
marks=d.get(name,-1) if marks==-1:
print("Student not found") else:
print("Marks of {} : {}".format(name,marks))
option=input("Do you want to find another student marks[yes/no]") if
option=="no":
break

Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.
Ex:
squares={x:x*x for x in range(1,6)}
print(squares)

Ex:
doubles={x:2*x for x in range(1,6)}
print(doubles)
Property List Tuple Set Dict
Insertion order Yes Yes No No
Duplicates are Yes Yes No No
allowed

Heterogeneous Yes Yes Yes Yes


objects are allowed

Is mutable or Mutable Immutable Mutable Mutable


immutable?

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