Skip to main content

Python Dictionary Notes

 Dictionary (Back to basics)


Definition:


1) Dictionaries are used to store data in key-value pair form.

     'name' : 'Lamborghini'

  so the 'name' is the key and 'Lamborghini' is the value.

  

2) A dictionary is a collection of ordered(in Python 3.7 or later) and unordered(in Python 3.6 or earlier). It does not allow duplicates.


 for example:

 {'name':'Bugatti','name':'Buggati' } not possible due to duplicate key value pair

 or

 {'name':'Alfa Romeo','name':'Maserati'} not possible due to duplicate key and if used then the second key-value pair is displayed instead of the first item.

3) Dictionaries are written within curly brakets and have key-value pairs

   

   car = {'brand':'Ford','model':'Mustang','year':1964}

   print(car)


4) Dictionary length - it determines how many items a dictionary has using the len() function. It is important to note that an item is key-value pair.

 so in the previous example 'model':'Mustang' is a item cause it is a key-value pair

 now if we apply the function to the previous example like:

 p = len(car)

 print(p)

5) The key of the dictionary can never be of any mutable datatype example list. **very important

     example:

     p = { ['Brands','Models']:"Koenigsegg ONE"}

     print(p)

 If you try to run the program you will get an error TypeError: unhashable type: 'list'

6)The key of the dictionary can only be of immutable datatypes example numbers,tuple and string.


 example:

   1)

   p = {('Brands','Models'):"Koenigsegg One"}

   print(p)

   

   2)

   p = {1:'Ford',2:'Mahindra',3:'TATA'}

   print(p)

   

   3)

   p ={'Ford':'Mustang','Chevrolet':'Camaro'}

   print(p)

   

7) To display a dictionary in proper format we need to use the module:

  import json (json stands for javascript object notation)

  then we need to use the function present inside the module that function is dumps()

  so we need to use like this:

  

  import json

  p = {'brand':'Mahindra','model':'XUV 700','year':2023}

  print(json.dumps(p,indent=2)

  

  it will be displayed in this format:

  {

   "brand": "Mahindra",

   "model": "XUV 700",

   "year": 2023

  }

  

8) Accessing items: To access the items of a dictionary by refering to its key name,inside square brackets.

 p={

  "brand": "Mahindra",

  "model": "XUV 700",

  "year": 2023

 }

 z = p["year"] 

 print(z)

 we will get 2023 as the answer

 we can do this in another way

 z = p.get("year")

 print(z)

9) To display only the keys of the dictionary we will use the function:

    z = p.keys()

 Output:

 dict_keys(['brand', 'model', 'year'])

10) To add new item to a dictionary 

     p["Price"]="20 lacs"

  so the dictionary will look like this 

 p={

  "brand": "Mahindra",

  "model": "XUV 700",

  "year": 2023,

  "Price":"16 lacs"

 }

 print(p)


11) The values() function will return a list of all the values in the dictionary

 z = p.values()

 print(z)

 Output:

 dict_values(['Mahindra', 'XUV 700', 2023, '16 lacs'])

12) The items() function will return each item in a dictionary, as tuple in a list 

 z = p.items()

 print(z)

 Output:

 dict_items([('brand', 'Mahindra'), ('model', 'XUV 700'), ('year', 2023), ('price', '16 lacs')])

13) Changing a value of a dictionary using key 

 p={

  "brand": "Mahindra",

  "model": "XUV 700",

  "year": 2023,

  "Price":"16 lacs"

 }

 so let's change the year to 2024

 p['year']=2024

 The dictionary will look something like this

 p={

  "brand": "Mahindra",

  "model": "XUV 700",

  "year": 2024,

  "Price":"16 lacs"

 }

14) Checking the presence of a key using "in" keyword

 p={

  "brand": "Mahindra",

  "model": "XUV 700",

  "year": 2024,

  "Price":"16 lacs"

 }

 if "year" in p:

  print("Oshnik will buy",p["brand"],p["model"])

  

 Output:

 Oshnik will buy Mahindra XUV 700

15) Updating a dictionaryusing update() method

 we need to pass key:value pairs to update a dictionary

 p = {

  'name':'Oshnik Kundu',

  'initials':'OK',

  'age':16

  }

 p.update({'age':17})

 print(p)

 Output: {'name':'Oshnik Kundu','initials':'OK','age'17}

16) Removing items from dictionary 

 There are different ways like pop(),popitem(),del,clear().

 (i) The pop() method removes the item with the specified key name

  p={"brand": "Mahindra","model": "XUV 700","year": 2023,"Price":"16 lacs"}

  p.pop("Price")

  print(p)

  Output:

  {"brand": "Mahindra","model": "XUV 700","year": 2023}

  

 (ii) The popitem() method removes the last item.

  p={"brand": "Mahindra","model": "XUV 700","year": 2023}

  p.popitem()

  print(p)

  

  Output:

  {"brand": "Mahindra","model": "XUV 700"}

  

 (iii) The del keyword removes the item with the specified key name:

  p={"brand": "Mahindra","model": "XUV 700","year": 2023}

  del p["model"]

  print(p)

  

  Output:

  {"brand": "Mahindra","year": 2023}

  

 (iv) The clear() method empties the dictionary

  p={"brand": "Mahindra","model": "XUV 700","year": 2023}

  p.clear()

  print(p)

  

  Output:

  {}  


17) Looping through a dictionary:

 You can loop through a dictionary using a for loop 

 (i) To print all the keys of the dictionary one by one

  p={"brand": "Mahindra","model": "XUV 700","year": 2023}

  for k in p:

   print(k)

  Output:

  brand

  model

  year

 (ii) To print all the values of the dictionary one by one

  p={"brand": "Mahindra","model": "XUV 700","year": 2023}

  for k in p:

   print(p[k])

  Output:

  Mahindra

  XUV 700

  2023

 (iii) To print key and values together one by one items

  for k,v in p.items():

   print(k,v)

   

  Output:

  brand Mahindra

  model XUV 700

  year 2023

Popular posts from this blog

Panagram ISC 2025 Specimen Practical Paper

import java.util.*; class panagram //ISC 2025 Practical Question {     //str for storing the sentence     String str;     panagram()     {         str="";     }     void accept()     {         Scanner sc=new Scanner(System.in);         System.out.println("Enter a sentence:");         str=sc.nextLine();     }     void panagramcheck()     {         int letters[]=new int[26];          StringTokenizer st=new StringTokenizer(str);         while(st.hasMoreTokens())         {             String w = st.nextToken().toUpperCase();             for(int i=65;i<=90;i++)             {                 for(int j=...

Program in Java: ISC Program CellPhone Keystrokes

import java.util.Scanner; public class Keypad {     public static void main(String args[])     {         //Array to hold keystrokes for each letter         int keys[] = new int[26];         //intialise         keys['A'-'A']=1; //A         keys['B'-'A']=2; //B         keys['C'-'A']=3; //C         keys['D'-'A']=1; //D         keys['E'-'A']=2; //E         keys['F'-'A']=3; //F         keys['G'-'A']=1; //G         keys['H'-'A']=2; //H         keys['I'-'A']=3; //I         keys['J'-'A']=1; //J         keys['K'-'A']=2; //K         keys['L'-'A']=3; //L         keys['M'-'A']=1; //M         keys['N'-'A']=2; //N       ...

ISC Program: Predict day of the week from date

Algorithm : 1)Take the last two digits of the year. 2)Divide by 4, discarding any fraction. 3)Add the day of the month. 4)Add the month's key value: JFM AMJ JAS OND 144 025 036 146 5)Subtract 1 for January or February of a leap year. 6)For a Gregorian date, add 0 for 1900's, 6 for 2000's, 4 for 1700's, 2 for 1800's; for other years, add or subtract multiples of 400. 7)For a Julian date, add 1 for 1700's, and 1 for every additional century you go back. 8)Add the last two digits of the year. 9)Divide by 7 and take the remainder. Example : Let's take a date: 26/03/2027 Last two digit of the year = 27 Divide by 4 discard fraction = 27/4 = 6.75 = 6 Add day = 6 + 26 = 32 Month key = 4 + 32 = 36 Add year code = 36 + 6 = 42 Now add two digits of the first year = 42 + 27 = 69 Now get the remainder after dividing by 7 = 69%7=6 So 1 is Sunday so 6 is Friday So 27/03/2027 Program : import java.util.Scanner; public class daydate {     public static void main(String[] arg...