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

File Handling Java Notes Class 11 ISC