11.Dictionary Datatype
11.Dictionary Datatype
Creating dictionary:
Empty dict:
d={} #d=dict()
d[100]='gangadhar' d[103]='lokesh' d[104]='rajesh'
print(type(d))
print(d)
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]))
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)
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))
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)
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()))
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)
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