INTRODUCTION: Dictionary
- A dictionary is like a list, but more in general. In a list, index value is an integer, while in a dictionary index value can be any other data type and are called keys. The key will be used as a string as it is easy to recall.
- A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences and hence maintain no left-to right order.
- It is an un-ordered collection of items where each item consist of a key and a value.
- It is mutable (can modify its contents ) but Key must be unique and immutable.
- Dictionary is also known as associative array or mapping or hashes .
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 value are separated by a colon (:).
Example: -
dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}
Accessing List Item
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict)
print ("Class : ", dict.get('Class'))
OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
('Class : ', 11)
Iterating Through A Dictionary
Following example will show how dictionary items can be accessed through loop.
Example: -
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
OUTPUT
Informatics Practices 11
Updating Dictionary Elements
We can change the individual element of dictionary.
Example: -
dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science'
OUTPUT
{'Class': 11, 'Subject': 'computer science'}
Deleting Dictionary Elements
del, pop() and clear() statement are used to remove elements from the dictionary.
del
Example: -
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
print('after dictionary delete', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after dictionary delete',
- pop() method is used to remove a particular item in a dictionary.
- clear() method is used to remove all elements from the dictionary.
Example: -
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
print('after item delete', dict)
print('after clear', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after clear', {})
Built-in Dictionary Functions
- len(dict) Gives the total length of the dictionary. It is equal to the number of items in the dictionary.
- str(dict) Return a printable string representation of a dictionary
- type(variable) If variable is dictionary, then it would return a dictionary type.
- Dict1= { } # this is an empty dictionary without any element.
- DayofMonth= { January”:31, ”February”:28, ”March”:31, ”April”:30, ”May”:31, ”June”:30, ”July”:31, ”August”:31, ”September”:30, ”October”:31, ”November”:30, ”December”:31}
- FurnitureCount = { “Table”:10, “Chair”:13, “Desk”:16, “Stool”:15, “Rack”:15 }
- By above examples you can easily understand about the keys and their values.
- One thing to be taken care of is that keys should always be of immutable type.
Built-in functions in Dictionary
SN |
Function |
Function Details and working |
1. |
len( ) |
Returns the
length of the Dictionary(key-value pair will be count as 1 ) Len(Mydict) |
2. |
dict( ) |
Creates Dictionary X=dict(name=”sunil”,age=30,country=”India” |
3. |
keys( ) |
Returns all available keys
x.keys() output: dict.keys([‘name’,’age’,’country’]) |
4. |
values() |
Returns all the available values. x.values( ) output: dict_values([‘sunil’,30,’India’]) |
5. |
get( ) |
The get() method returns the value of the item
with the specified key Mydict
={'Name': 'Raj', 'Age': 15, 'Class': 12,'Totalmarks':450} print(Mydict.get('Class')) print(Mydict['Name']) |
6. |
update():- |
updates the dictionary with the elements from another dictionary objector from an iterable of key/value pairs mydict = {'Africa':200,'australia':300,'England':400} mydict.update({'China':500}) |
7. |
del() |
The del keyword can be used to in-place delete the key that is present inthe
dictionary in Python. test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21} removes Mani del test_dict['Mani'] |
8. |
pop() |
method
removes the specified item from the dictionary and return thecorresponding value. Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12,
'Totalmarks':450} Mydict.pop('Name') |
9. |
popitem():- |
The popitem()
method removes the item that was last inserted into thedictionary. Mydict = {'Name': 'Raj', 'Age': 15, 'Class': 12,
'Totalmarks':450} K= Mydict.popitem() print("Last
item of dictionary = ", K) |
10. |
fromkeys() |
The dict.fromkeys()
method creates a new dictionary from the given iterable (string, list, set, tuple)
as keys and with the specified value. keys = ('Mumbai','Bangalore','Chicago','New
York') value = 'city' dictionary
= dict.fromkeys(keys, value) |
11. |
copy( ) |
copy()
method returns a copy (shallow copy) of the original dictionary original={'Name':
'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450} new =
original.copy() print('Orignal: ', original) print(‘New:’,new) |
12. |
setdefault( ) |
The
setdefault() method returns the value of a key (if the key is in dictionary).
If not, it inserts key with a value to the dictionary. romanNums = {'I':1, 'II':2,
'III':3, 'IV':4, 'V':5 } value =
romanNums.setdefault('I') print("The return value is: ", value) value
= romanNums.setdefault('VI') print("The return value is: ",value) print("Updated
dictionary: ",romanNums) |
13. |
max( ) & min( ) |
Used to find
maximum and minimum respectively fromthe dictionary. my_dict =
{'x':500, 'y':5874, 'z': 560} key_max =
max(my_dict.keys(), key=(lambda k: my_dict[k])) key_min = min(my_dict.keys(),
key=(lambda k: my_dict[k])) print('Maximum
Value: ',my_dict[key_max]) print('Minimum Value: ',my_dict[key_min]) |
14. |
clear() |
removes all
items from the dictionary. Mydict
={'Name': 'Raj', 'Age': 15, 'Class': 12, 'Totalmarks':450} Mydict.clear() print(Mydict) |
15. |
sorted( ) |
The sorted()
function returns a sorted list of the specified iterable object dict = {6:'George'
,2:'John' ,1:'Potter' ,9:'Micheal' ,7:'Robert' ,8:'Gayle' } b = sorted(dict.keys()) print("Sorted
keys",b) c = sorted(dict.items()) print("Sorted
Values",c) |
3. Write a program to count the number of times a character appears in a given string.
Output
4. Write a program to convert a number entered by the user into its corresponding number in words. for example if the input is 876 then the output should be ‘Eight Seven Six’.
5. Count the number of times, a character appears in a given string using a dictionary :
#initializing string
# using dict.get() to get count # of each element in string
for keys in test_str:
res[keys] = res.get(keys, 0) + 1 # printing result
print ("Count of all characters in GeeksforGeeksis : \n" , res)
6. Create a dictionary with names of employees, salary and access them.
Mydict = { }
name = input("Enter employee name :-") sl = int(input("Enter employee salary :-"))
Mydict[ name] = sl
user = input("Do you want to quit then enter yes :-") if user == "yes" :
break;
print(Mydict)
Short Answers
type questions[1 mark]
Q1. Keys of dictionary must be
(a) antique (b)unique (c) mutable (d) integers
a. True b. False
Q3. Key – value concept is in
(a) List (b)String (c)Dictionary (d)Tuple
a={'a' : "Apple", 'b' : "Banana" , 'c' : "Cat"} print(a[1])
Q5. Write the two ways to construct an empty dictionary.
sales = {'Audi':45, 'BMW':32, 'Ferrari':12}
for x in sales:
print(x)
Q7. Suppose a dictionary days is declared as:
days={1:"Sun", 2:"Mon", 3:"Wed"}
Write a statement in Python to change Wed to Tue.
Q.8. is used to remove all items form a particular dictionary.
Q.9. What will be the output:-
d1={‘rohit’:56,” Raina”:99}
print(“Raina” in d1)
Q10. Which of the following function create a dictionary from sequence of key - valuePairs.
(a) dictionary( ) (b) dict( ) (c) create( ) (d) convert( )
Short Answer Type Questions [2 marks]
Q1. Parth wants to display the value corresponding to the key “3” in dictionary given
below. As a friend of Parth, help him to find the correct code.
(a) print(D.get(3)) (b) print(D[3]) (c) Both of the above (d) None of the above
keys = ['Ten', 'Twenty', 'Thirty'] values = [10, 20, 30]
Q3. Print the value of key ‘physics’ from the following dictionary
MyDict = {"class": {"student": {"name": "Mike","marks": {"physics": 70,"history": 80}}}}
My_dict = {'Physics': 82,'Math': 65,'CS': 75}
Q5. Find the output of the following python code:-
a = {}
a[1] = 1
a['1'] = 2
a[1]= a[1]+1
count = 0
count += a[i]
Q6. What is the output of the following of code?
print (a)
Q7. What will be output of following python program :-
dict = {(3,4,8):4,(5,6,9):3}
print(dict)
Q8. Find the output of the following code:-
dictlang = {'c#': 6, 'GO': 89, 'Python':4,'Rust':10}cpydict = dictlang.copy() print(cpydict)
Q9. Find the output of the following code:-
fruitsDict = {'Apple': 100,'Orange': 200,'Banana': 400, 'pomegranate':600 }
del fruitsDict['Apple']
print('Dict after deleting key =',fruitsDict)
Q10. Create a dictionary ‘ODD’ of odd numbers between1 and 10, where the key is the decimal number and the value is the corresponding number in words.
Long Answer Type Question[3 & 4 mark Questions]
1) Answer the following question on the given dictionary
(i) Add a new key(‘City) with value “Jaipur” in Employee dictionary
(ii) Display all the keys of the Employee dictionary
(iii) Write code to delete all the items of the Employee dictionary
2) What are the differences between dictionary and list?
3) Consider the following dictionary capitals
capitals ={ "Maharashtra": "mumbai","Delhi" : "New Delhi","Uttar pradesh":"Lucknow"}
Find the output of the following
statements:-
(i)
print(capitals.get("Lucknow"))
(ii)
print(capitals.keys())
(iii)
print("Delhi" in capitals)
5) Python Program to Multiply All the Items in a Dictionary.
6) Write a Python program to print all unique values in a dictionary.
{"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}
7) Write a program to create a dictionary namely Mydict with 10 keys 0 to 9, each having value as 20. Update the first and last values by adding 100 to each of them.
8) Write a python function to print sum of all items in a dictionary.
Case Based Questions
1. Mohan is student who is learning python programming. Mohan is unable to find out the output of the following python program. Help the Mohan by finding outputof the following :-
Mydict= {'A':10,'B':20,'a':30, 'D':40}
Val_A= ''
for i in Mydict: if (i>Val_A):
Val_A= i
Val_B= Mydict[i]
print(Val_A) # Line1
print(Val_B) # Line2
print(20 in Mydict) # Line3
Mylist.sort() # Line5
print(Mylist[-1]) # Line6
(i) What output does Line1 produce ?
(ii) What output does Line2 produce ?
(iii) What output does Line3 produce ?
(iv) What output does Line4 produce ?
(vi) What output does Line6 produce ?
(i) Create a dictionary student which ask Student roll number, Name and Marksof students and display them in tabular format.
(ii) Display the names of those students who have secured marks more than 75.
(iii) Delete those students who have secured less than 50 marks.
ANSWER KEY
|
Short Answer Type
Questions [1 Marks] |
|||
1. |
B |
|||
2. |
A |
|||
3. |
C |
|||
4. |
KEY ERROR |
|||
5. |
(i) Use of {} symbol dict()function |
|||
6. |
Audi BMW Ferrari |
|||
7. |
Days[3]=”Tue” |
|||
8. |
clear() |
|||
9. |
A |
|||
10. |
True |
|||
|
Short Answer Type
Questions [2 Marks] |
|||
1. |
D |
|||
2. |
keys = ['Ten', 'Twenty', 'Thirty']values = [10, 20, 30] res_dict = dict(zip(keys, values)) print(res_dict) |
|||
3. |
print(MyDict['class']['student']['marks']['physics']) |
|||
4. |
print(min(My_dict, key=My_dict.get)) |
|||
5. |
count= 4 |
|||
6. |
{0: 0, 1:
1, 2: 8, 3: 27, 4:
64, 5: 125} |
|||
7. |
{(3, 4, 8):
4, (5, 6, 9):
3} output: 3 |
|||
8. |
{'c#': 6, 'GO': 89, 'Python': 4, 'Rust': 10} |
|||
9. |
Dict after deleting key = {'Orange': 200, 'Banana': 400,'pomegranate': 600} |
|||
10. |
ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'} print(ODD) |
|||
Long Answer type
questions |
||||
1. |
(i)
Employee['City']= "Jaipur" print(Employee) (ii)
Employee.keys() (iii)
Employee.clear() |
|||
2. |
1.
List is an ordered set of
elements. But, a dictionary is a data structure that is used for matching one element (Key) with another (Value). 2.
The index values can be used to
access a particular element. But, in dictionary key represents index. Remember that, key may be a number of a
string. 3. Lists are used to look up a
value whereas a dictionary is used to take one value and look
up another value. |
|||
3. |
(i)
None (ii)
dict_keys(['Maharashtra', 'Delhi', 'Uttar pradesh', 'Tamil Nadu ' (iii) True |
|||
4. |
num = input("Enter any number: ") #number is stored
as string#numberNames is a dictionary of digits and corresponding
number#names numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\ 5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'} result = '' for ch in num: key = int(ch) #converts character to integerrvalue = numberNames[key] result = result + ' ' + value print("The number is:",num) print("The numberNameis:",result) |
|||
5. |
My_dict = {'A':10, 'B':20, 'C':30} Multiply= 1 for i in My_dict: Multiply= Multiply*My_dict[i]print(Multiply) |
|||
6. |
L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI":"S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}] print("Original List:
",L) u_value = set(
val for dic in L for val in dic.values()) print("Unique Values:
",u_value) |
|||
7. |
Mydict= dict.fromkeys(range(10), 20)
Mydict[0]+=20 Mydict[9]+= 20 print(Mydict) |
|||
8. |
# Function to
print sum def ReturnSum(myDict): list = [] for i in myDict: list.append(myDict[i]) final = sum(list) return final dict = {'a': 100,
'b': 200, 'c': 300} print("Sum :", ReturnSum(dict)) |
|||
9. |
def CountFrequency(my_list): # Function definition# #Creating an empty dictionary freq = {} for item in
my_list: if (item in freq): freq[item] += 1 else: freq[item] = 1 for key, value in
freq.items(): print ("% d
: % d"%(key, value)) my_list=[1, 1,
1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list) # Function calling |
|||
10. |
D1= { } i=1 Num= int (input("Enter number of entries: ")) while (i<=Num): a= input("Enter name: ") b= input("Enter age:") D1[a]=b i= i+1 L= D1.keys() for
i in L: print(i, '\t', D1[i]) |
|||
Case Based
Question |
|
|||
1. |
(i)
A (ii)
30 (iii)
False (iv)
True (v) None (vi) ('a', 30) |
|
||
2. |
(i) n=int(input("How many student data you want to enter ...")) Student={} for i in range(n): roll_no=int(input("Enter roll no:")) name=input("Enter name: ") marks=int(input("Enter
marks: ")) Student[roll_no]=[name,marks] print("{:<10} {:<10} {:<10}".format('Rollno','Name','Marks')) for k, v in d.items(): name, num = k, v print(name, marks)) (ii) n=int(input("Enter n: ")) d={} for i in range(n): roll_no=int(input("Enter roll no: ")) name=input("Enter name: ") marks=int(input("Enter marks: ")) d[roll_no]=[name,marks] for k in d: if(d[k][1]>75): print(d[k][0]) (iii) n=int(input("How many student data you want to enter ...")) Student={} for i in range(n): roll_no=int(input("Enter roll no: ")) name=input("Enter name: ") marks=int(input("Enter marks: ")) Student[roll_no]=[name,marks] for k, v in list(Student.items()): if v[1] < 50: del Student[k] print("Remaining students: ", Student) |
|
No comments:
Post a Comment