Dictionaries
Dictionaries
k= dict.fromkeys((1,2,3),(4,5,6))
Output:
{1: (4, 5, 6), 2: (4, 5, 6), 3: (4, 5, 6)}
K=dict.fromkeys((1,2,3))
Output
{1: None, 2: None, 3: None}
Practice Question
Q1. An Institute has decided to
deposit scholarship amount of
Rs.2000/- to some students. Write a
program to input the selected
students’ roll no and create a
dictionary for the same.
Output :
{10:2000,25:2000,30:2000}
setdefault() method
It inserts a new key:value pair ONLY IF the key doesn’t already exist.
If the key exist, it returns the current value of the key. The existing
value of the key will not be updated
dict.setdefault(<key>,<value>)
Marks={1:30,2:40,3:50}
Marks.setdefault(4,20)
{1:30,2:40,3:50,4:20} #new key:value added
Marks.setdefault(2,50)
{1:30,2:40,3:50,4:20} #no change
popitem()
This method removes and returns the last key:value pair from
the dictionary.
It follows the LIFO (Last IN First Out) structure.
This method accepts no parameter.
Syntax - <dict>.popitem()
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d.popitem()
Here it will return (4,’Mohan’) as output.
If the dictionary is empty, calling popitem() raises a KeyError
Exercise
Write a program to delete the keys of a dictionary, one by one in LIFO
order. Make sure that there is no error generated after the last item
delete.
Sorted()
This method is used to sort the specified keys or
values. It will accept two parameters: One is the
dictionary object and second is the reverse.
The default value of reverse is False.
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sorted(d))
The above code will return the list of keys as :
[2, 4, 11, 30]
If you want to sort keys in descending order
use reverse=True.
Observe this:
Sorted() d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sorted(d, reverse=True))
Sorted() function will return the sorted result always in list form.
It will return the maximum key or
value as specified in the code.
Observe this example:
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Moha
max() n"}
print(max(d))
print(max(d.values()))
The second line returns 30 and the
third line returns ‘Vatsal’.
min()
It will return the minimum key or value as
specified in the code. Observe this
example.
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(min(d))
print(min(d.values()))
It will make the sum of all the
specified keys or values.
Example:
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Moha
Sum() n"}
print(sum(d))
47
copy()
It is used to create a shallow copy of a dictionary.
Shallow copy refers to copying upper layers rather than inner objects.
The example is as follows:
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d1=d.copy()
Output
{'rno': 1, 'name': 'Aman', 'age': 12}
Q1. Write a Python script to generate and print a dictionary that
contains a number (between 1 and n) in the form (x, x*x).
Sample Dictionary ( n = 5) :
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Q2. Write a Python program to sum all the items in a dictionary.
Ans1.
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Ans2.
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
Consider the following dictionary stateCapital:
stateCapital={"AndraPradesh":"Hyderabad","Bihar":"Patna","Maharashtra":"
Mumbai","Rajasthan":"Jaipur"}
Find the output of following statements:
print(stateCapital.get('Bihar'))
print(stateCapital.keys())
print(stateCapital.values())
print(stateCapital.items())
print(len(stateCapital))
print("Maharashtra" in stateCapital)
print(stateCapital.get("Assam"))
del stateCapital["AndraPradesh"]
print(stateCapital)
Output -
Patna
dict_keys(['AndraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
dict_items([('AndraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra',
'Mumbai'), ('Rajasthan', 'Jaipur')])
4
True
None
{'Bihar': 'Patna', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'}
Q1. Given the dictionary d={‘k1’:’v1’, ‘k2’:’v2’, ‘k3’:’v3’}, Create a dictionary
with opposite mapping i.e. write a program to create the dictionary as :
Inv_d={’v1’:’k1’, ’v2’: ’k2’, ‘v3’:’k3’}
Q2. Write a program that checks if two same value in a dictionary have
different keys. That is, for dictionary
D1={ ‘a’:10, ‘b’:20, ‘c’:10}
The program should print “2 keys have same values” and for
D2={‘a’:10, ‘b’:20, ’c’:30}
The program should print “No keys have same values”
Ans1.
d={'k1':'v','k2':'v2','k3':'v3'}
inv_d = {}
for k, v in d.items():
inv_d[v] = inv_d.get(v,[]) + [k]
print(inv_d)