Dictionaries

Dictionaries:

Dictionaries are collections of associated pairs of items where each pair consists of a key and a value. This key-value pair is typically written as key:value. Dictionaries are written as comma-delimited key:value pairs enclosed in curly braces.

Using a Dictionary:

It is important to note that the dictionary is maintained in no particular order with respect to the keys. The first pair added (‘Utah’: ‘SaltLakeCity’) was placed first in the dictionary and the second pair added (‘California’: ‘Sacramento’) was placed last. The placement of a key is dependent on the idea of “hashing,” Dictionaries have both methods and operators.

Operators Provided by Dictionaries in Python
Operator Use Explanation
[] myDict[k] Returns the value associated with k, otherwise its an error
In key in adict Returns True if key is in the dictionary, False otherwise
Del del adict[key] Removes the entry from the dictionary

 

 

phoneext={‘david’:1410,’brad’:1137}>>> phoneext{‘brad’: 1137, ‘david’: 1410}>>> phoneext.keys()dict_keys([‘brad’, ‘david’])>>> list(phoneext.keys())[‘brad’, ‘david’]>>> phoneext.values()dict_values([1137, 1410])>>> list(phoneext.values())[1137, 1410]>>> phoneext.items()dict_items([(‘brad’, 1137), (‘david’, 1410)])>>> list(phoneext.items())[(‘brad’, 1137), (‘david’, 1410)]>>> phoneext.get(“kent”)>>> phoneext.get(“kent”,”NO ENTRY”)

‘NO ENTRY’

Example :Write the python code in one program:
  • Create a Class data type called Student()
  • Write two functions/methods as part of the class:
    1. addStudentInfo() – adding a student data and
    2. retrieveStudentInfo() – retrieving student information.
  • Insert Three students records. Data is given below.
  • Print the student data whose admission year is 2019
Use the following data:
                     Class structure: Student Name, Student Id, Course Name, Faculty Name, Credit, AdYear)
                     Student Records : (‘ Jaya Kumar’, 1200, ‘DBMS’, ‘Seema’, 4, 2019),
                                                      (‘ Vijaya ’, 1300, ‘DS’, ‘John’, 4, 2020)
                                                      (‘ Jaya ’, 2300, ‘Maths, ‘KSR’, 4, 2019)