By: Vinay Agrawal
Dictionary  Dictionary is Mutable.  Elements are arranged in the form of key-value pairs.  The symbol used to represent Dictionary is {} eg. d=:{‘Aman’:6.7, ’Raj’:9.5, ’Madhav’:8.6} key value  Key and its value is separated by a colon :
 Keys must be immutable (may be string, tuple, number).  Values may be immutable or mutable.  General syntax of dictionary is as follows:- d={key1:value1,key2:value2,…….keyn:valuen}  Elements are ordered (After 3.7 Version)  It does not have the concept of numeric indexing, but it has the concept of key indexing. eg. print(d[key])
Q1. How we can create empty dictionary? Ans. d={} OR d=dict()
Accessing Values d={‘Aryan’:8.5, ’Madhav’:9.5, ’Dev’:6.5} print(d[‘Aryan’]) print(d.get(‘Dev’)) print(d[‘madhav’]) O/P: 8.5 6.5 Error
Dictionary is Mutable Adding elements in Dictionary  d[key]=value  d1.update(d2)- Adds the elements of d2 to the elements of d1. d1={‘Aman’:6.2, ‘Ajay’:8.2} d2={‘Madhav’:5.5, ‘Manav’:6.6} d1.update(d2)
Deleting elements from dictionary  d.pop(key [, defaultvalue]) :- In this, it will delete the key-value pair based on provided key. 2nd parameter is optional, If it is there, it will return if key does not exist.  d.popitem() :- It removes the item that was last inserted into the dictionary. In versions before 3.7,it removes a random item. The removed item is the return value in the form of tuple.
 d.clear() :- It will empties the dictionary.  del d[key] :-It will delete the key-value pair based on key.
Modifying the value of dictionary  d[key]=value
Methods of Dictionary  d.copy()  d.get(key[,value]): To access value of dictionary.  d.keys():- It will give list of all keys present in dictionary.  d.values():-It will give list of all values present in dictionary.  d.items():- It will give list of all keys,values present in dictionary. Return List of tuples.  d.has_key(key):-It works in Python 2.x version. Use in operator in Python 3.x
 d.fromkeys(seq[,value]):- This will help in creating a dictionary  d.setdefault(key,value)  len(d)  sorted(x):- x may be d.keys() or d.values()  zip(l1,l2) :  dict()
Looping over a Dictionary d={‘amit’:6.5, ‘raj’:9.1,’madhav’:7.8} for i in d: print(i) for i in d: print(i,’ ‘,d[i]) for i, j in d.items(): print(i,’ ‘,j) for i in d.items(): print(i)
Dictionary Comprehension  d={i:i*i for i in range(10)}  D={x:2*x for x in range(1,5)}
Programs 1.WAP that creates a dictionary of radius of a circle and its circumference. Expected O/P: Enter -1 to exit Enter radius:5 Enter radius:7 Enter radius:8 Enter radius:-1 {5:31.4, 8:50.24,7:43.96}
2.WAP that prints the histogram of frequencies of characters occurring in a message. Expected O/P: Hello Hi H ** e * l ** o * * i *
3. WAP to invert the dictionary( i.e keys becomes values and vice-versa) 4.WAP that has dictionary of names of students and a list of their marks in 4 subjects. Create another dictionary from this dictionary that has name of the students and their total marks. Find out the topper and his/her score.
5. Write a Program to store a sparse matrix as a dictionary. Assume Sparse Matrix 0 1 2 3 4 0 0 0 0 1 0 1 2 0 0 0 3 2 0 0 0 4 0 Expected O/P: Sparse Matrix represented as dictionary: {(0,3):1, (2,3):4, (1,0):2, (1,4):3}
6. WAP that prompts the user to enter a message. Now count and print the number of occurrences of each character. 7. WAP that creates a dictionary of cubes of odd numbers in the range 1-10. 8. WAP that enter string and then find the frequency of each word and represent in the form of dictionary.
Nested Dictionary OrangeCap Example (Find Top-Scorer along with score) D={ 'match1':{ ‘Virat':57, ‘Dhoni’:38 }, 'match2':{ ‘Maxwell':9, ‘Virat':42 }, 'match3':{ ‘Dhoni':41, ‘Taylor':63, ‘Maxwell’:91 } }
Solution D={ 'match1':{ 'Virat':57, 'Dhoni':38 }, 'match2':{ 'Maxwell':9, 'Virat':42 }, 'match3':{ 'Dhoni':41, 'Taylor':63, 'Maxwell':91 } } x=D.values() D1={} print(x) for i in x: for j in i: if j in D1: D1[j]=D1[j]+i[j] else: D1[j]=i[j] print(D1) k=max(D1,key=D1.get) print("Player Name is ",k) print("Score is ",D1[k])
Some More Programs….. 1. WAP that has a dictionary of words in English Language and their corresponding words in Hindi. Define another Dictionary that has a list of words in Hindi and their corresponding words in Urdu. Take all words from English Language and display their meaning in both the languages. d1={‘Teacher’:’Shikshak’, ‘Book’:’Pustak’,’Friend’:’Mitr’} d2={‘Shikshak’:’Adhyapak’,’Pustak’:’Kitab’,’Mitr’:’Dost’} Expected O/P: Teacher in Hindi means Shikshak and in Urdu means Adhaypak Book in Hindi means Pustak and in Urdu means Kitab Friend in Hindi means Mitr and in Urdu means Dost
2. WAP that creates two dictionaries. One that stores conversion values from meters(1-5) to centimeters and other that stores values from centimeters to meters. Expected O/P: Meters to Centimeters {1:100,2:200,3:300,4:400,5:500} Centimeters to Meters {100:1,200:2,300:3,400:4,500:5}
3.WAP that has a dictionary of states and their codes. Add another state in the pre-defined dictionary, print all the items in the dictionary and try to print code for a state that does not exist. Use setdefault() method states={‘Rajasthan’:101,’Haryana’:102} Expected O/P: {‘Rajasthan’:101,’Haryana’:102,’Assam’:103} None {‘Rajasthan’:101,’Haryana’:102,’Assam’:103,’Goa’:104}

Dictionarys in python programming language.ppt

  • 1.
  • 2.
    Dictionary  Dictionary isMutable.  Elements are arranged in the form of key-value pairs.  The symbol used to represent Dictionary is {} eg. d=:{‘Aman’:6.7, ’Raj’:9.5, ’Madhav’:8.6} key value  Key and its value is separated by a colon :
  • 3.
     Keys mustbe immutable (may be string, tuple, number).  Values may be immutable or mutable.  General syntax of dictionary is as follows:- d={key1:value1,key2:value2,…….keyn:valuen}  Elements are ordered (After 3.7 Version)  It does not have the concept of numeric indexing, but it has the concept of key indexing. eg. print(d[key])
  • 4.
    Q1. How wecan create empty dictionary? Ans. d={} OR d=dict()
  • 5.
    Accessing Values d={‘Aryan’:8.5, ’Madhav’:9.5,’Dev’:6.5} print(d[‘Aryan’]) print(d.get(‘Dev’)) print(d[‘madhav’]) O/P: 8.5 6.5 Error
  • 6.
    Dictionary is Mutable Addingelements in Dictionary  d[key]=value  d1.update(d2)- Adds the elements of d2 to the elements of d1. d1={‘Aman’:6.2, ‘Ajay’:8.2} d2={‘Madhav’:5.5, ‘Manav’:6.6} d1.update(d2)
  • 7.
    Deleting elements fromdictionary  d.pop(key [, defaultvalue]) :- In this, it will delete the key-value pair based on provided key. 2nd parameter is optional, If it is there, it will return if key does not exist.  d.popitem() :- It removes the item that was last inserted into the dictionary. In versions before 3.7,it removes a random item. The removed item is the return value in the form of tuple.
  • 8.
     d.clear() :-It will empties the dictionary.  del d[key] :-It will delete the key-value pair based on key.
  • 9.
    Modifying the valueof dictionary  d[key]=value
  • 10.
    Methods of Dictionary d.copy()  d.get(key[,value]): To access value of dictionary.  d.keys():- It will give list of all keys present in dictionary.  d.values():-It will give list of all values present in dictionary.  d.items():- It will give list of all keys,values present in dictionary. Return List of tuples.  d.has_key(key):-It works in Python 2.x version. Use in operator in Python 3.x
  • 11.
     d.fromkeys(seq[,value]):- Thiswill help in creating a dictionary  d.setdefault(key,value)  len(d)  sorted(x):- x may be d.keys() or d.values()  zip(l1,l2) :  dict()
  • 12.
    Looping over aDictionary d={‘amit’:6.5, ‘raj’:9.1,’madhav’:7.8} for i in d: print(i) for i in d: print(i,’ ‘,d[i]) for i, j in d.items(): print(i,’ ‘,j) for i in d.items(): print(i)
  • 13.
    Dictionary Comprehension  d={i:i*ifor i in range(10)}  D={x:2*x for x in range(1,5)}
  • 14.
    Programs 1.WAP that createsa dictionary of radius of a circle and its circumference. Expected O/P: Enter -1 to exit Enter radius:5 Enter radius:7 Enter radius:8 Enter radius:-1 {5:31.4, 8:50.24,7:43.96}
  • 15.
    2.WAP that printsthe histogram of frequencies of characters occurring in a message. Expected O/P: Hello Hi H ** e * l ** o * * i *
  • 16.
    3. WAP toinvert the dictionary( i.e keys becomes values and vice-versa) 4.WAP that has dictionary of names of students and a list of their marks in 4 subjects. Create another dictionary from this dictionary that has name of the students and their total marks. Find out the topper and his/her score.
  • 17.
    5. Write aProgram to store a sparse matrix as a dictionary. Assume Sparse Matrix 0 1 2 3 4 0 0 0 0 1 0 1 2 0 0 0 3 2 0 0 0 4 0 Expected O/P: Sparse Matrix represented as dictionary: {(0,3):1, (2,3):4, (1,0):2, (1,4):3}
  • 18.
    6. WAP thatprompts the user to enter a message. Now count and print the number of occurrences of each character. 7. WAP that creates a dictionary of cubes of odd numbers in the range 1-10. 8. WAP that enter string and then find the frequency of each word and represent in the form of dictionary.
  • 19.
    Nested Dictionary OrangeCap Example (FindTop-Scorer along with score) D={ 'match1':{ ‘Virat':57, ‘Dhoni’:38 }, 'match2':{ ‘Maxwell':9, ‘Virat':42 }, 'match3':{ ‘Dhoni':41, ‘Taylor':63, ‘Maxwell’:91 } }
  • 20.
    Solution D={ 'match1':{ 'Virat':57,'Dhoni':38 }, 'match2':{ 'Maxwell':9, 'Virat':42 }, 'match3':{ 'Dhoni':41, 'Taylor':63, 'Maxwell':91 } } x=D.values() D1={} print(x) for i in x: for j in i: if j in D1: D1[j]=D1[j]+i[j] else: D1[j]=i[j] print(D1) k=max(D1,key=D1.get) print("Player Name is ",k) print("Score is ",D1[k])
  • 21.
    Some More Programs….. 1.WAP that has a dictionary of words in English Language and their corresponding words in Hindi. Define another Dictionary that has a list of words in Hindi and their corresponding words in Urdu. Take all words from English Language and display their meaning in both the languages. d1={‘Teacher’:’Shikshak’, ‘Book’:’Pustak’,’Friend’:’Mitr’} d2={‘Shikshak’:’Adhyapak’,’Pustak’:’Kitab’,’Mitr’:’Dost’} Expected O/P: Teacher in Hindi means Shikshak and in Urdu means Adhaypak Book in Hindi means Pustak and in Urdu means Kitab Friend in Hindi means Mitr and in Urdu means Dost
  • 22.
    2. WAP thatcreates two dictionaries. One that stores conversion values from meters(1-5) to centimeters and other that stores values from centimeters to meters. Expected O/P: Meters to Centimeters {1:100,2:200,3:300,4:400,5:500} Centimeters to Meters {100:1,200:2,300:3,400:4,500:5}
  • 23.
    3.WAP that hasa dictionary of states and their codes. Add another state in the pre-defined dictionary, print all the items in the dictionary and try to print code for a state that does not exist. Use setdefault() method states={‘Rajasthan’:101,’Haryana’:102} Expected O/P: {‘Rajasthan’:101,’Haryana’:102,’Assam’:103} None {‘Rajasthan’:101,’Haryana’:102,’Assam’:103,’Goa’:104}