E-Books

πŸ“— Python Dictionaries

Dictionaries are used to store data values in key:value pairs and written with curly brackets, where each key is unique and maps to a value.


  student = {
      "name": "Deepak",
      "age": 25,
      "course": "Python"
  }
  
  print(student)            
            

πŸ“— Dictionary type() in Python

From Python's perspective, dictionaries are defined as objects with the data type <class 'dict'>


  my_dict = {"name": "Deepak", "age": 21}
  print(type(my_dict))              
            

πŸ“— Ordered of Dictionaries in Python

Starting from Python 3.7, dictionaries maintain the insertion order of items. This means the order in which items are added to the dictionary is preserved.


  my_dict = {"name": "Deepak", "age": 21, "course": "Python"}

  for key, value in my_dict.items():
      print(key, value)              
            

πŸ“— Duplicates in Python Dictionaries

Dictionaries in Python do not allow duplicate keys. Values can be duplicates. If you try to insert a duplicate key, the value of the key is overwritten with the new value.


  my_dict = {"name": "Deepak", "age": 21, "nickname": "Deepak"}

  # Adding a duplicate key with a new value
  my_dict["name"] = "Raj"
              
  # Printing the updated dictionary
  print(my_dict)
            

πŸ“— Data Types in Python Dictionaries

A Python Dictionary allows you to store values of any data type as values, while the keys must be of an immutable data type (e.g., strings, numbers, tuples).

πŸ”‘ Key Data Types :


  # Valid keys: string, integer, tuple
  my_dict = {
      "name": "Deepak",      # String as key
      42: "Answer",          # Integer as key
      (1, 2): "Tuple Key"    # Tuple as key
  }
  
  print(my_dict)              
            


πŸ“š Value Data Types


  my_dict = {
      "name": "Deepak",        # String value
      "age": 21,               # Integer value
      "hobbies": ["coding", "reading"],  # List as value
      "address": {"city": "Delhi", "state": "Delhi"}  # Dictionary as value
  }
  
  print(my_dict)            
            

πŸ“— Dictionaries are Changeable (Mutable) in Python

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.


  student = {"name": "Deepak", "age": 21}
  student["course"] = "Python" # Add a new key-value pair
  student["age"] = 25 # Update an existing value
  del student["name"] # Delete a key-value pair
  print(student)              
            

πŸ“— Dictionary Length in Python

You can find the number of key-value pairs in a dictionary using the built-in len() function.


    student = {
      "name": "Deepak",
      "age": 21,
      "course": "Python"
  }
  
  print(len(student))            
            

πŸ“— The dict() Constructor in Python

Python provides a built-in dict() constructor to create dictionaries in a clean and flexible way.

Using Keyword Arguments


  student = dict(name="Deepak", age=21, course="Python")
  print(student)              
            


Using List of Tuples


  student = dict([("name", "Deepak"), ("age", 21), ("course", "Python")])
  print(student)              
            


Using Tuple of List


  data = (["name", "Deepak"], ["age", 21])
  d = dict(data)
  print(d)                           
            


Using Zipped Lists


  keys = ["name", "age", "course"]
  values = ["Deepak", 21, "Python"]
  student = dict(zip(keys, values))
  print(student)
            

πŸ“— Nested Dictionaries in Python

A nested dictionary is a dictionary inside another dictionary.


  myfamily = {
    "child1": {
      "name": "Aarav",
      "age": 15 
    },
    "child2": {
      "name": "Ishita",
      "age": 13 
    },
    "child3": {
      "name": "Kabir",
      "age": 11 
    }
  }              
            

πŸ“— Access Dictionary Items in Python

You can access the items of a dictionary by referring to its key name, inside square [ ]brackets:

Note: If the key doesn’t exist, it raises a ❌ KeyError.


  student = {"name": "Deepak", "age": 21}
  print(student["name"])              
            

πŸ“— Add Dictionary Items in Python

Adding items to a dictionary is simple β€” just assign a new key-value pair.


  student = {"name": "Deepak", "age": 21}
  student["course"] = "A Level"
  print(student)              
            

πŸ“— Change Dictionary Items in Python

You can update or modify existing dictionary values using their keys.


  student = {"name": "Deepak", "age": 21}
  student["age"] = 25
  print(student)              
            

πŸ“— Remove Dictionary Items in Python

The del keyword removes the specific item with the specified key name or deletes the entire dictionary.


  student = {"name": "Deepak", "age": 21}
  del student["name"]
  print(student)

  del student
  print(student)
            

πŸ“— Traversing Dictionary Items in Python

Traversing a dictionary means looping through its keys, values, or both by using a for loop.

βœ… 1. Loop Through Keys


  student = {"name": "Deepak", "age": 25, "city": "Sultanpur"}

  for key in student:
      print(key)              
            


βœ… 2. Loop Through Values


  student = {"name": "Deepak", "age": 25, "city": "Sultanpur"}

  for key in student:
      print(student[key])          
            


βœ… 3. Loop Through Keys and Values


  student = {"name": "Deepak", "age": 25, "city": "Sultanpur"}
  
  for key in student:
      print(key, ":", student[key])          
            

πŸ“— Sorting Key and Value of Dictionary in Python

You can sort a dictionary in Python by keys or values, in ascending or descending order using the built-in sorted() function.

βœ… Sort by Keys Ascending Order


  students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}

  for key in sorted(students):
      print(key,' : ',students[key])              
            


βœ… Sort by Keys Descending Order


  students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}

  for key in sorted(students, reverse=True):
      print(key,' : ',students[key])
            


βœ… Sort by Values Ascending Order


  students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}

  for  key in sorted(students, key=students.get):
      print(key,':',students[key])
            


βœ… Sort by Values Descending Order


  students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}

  for  key in sorted(students, key=students.get, reverse=True):
      print(key,':',students[key])
            


πŸ“— Dictionary Methods in Python

Python has a set of built-in methods that you can use on dictionaries.

Method Description Example
get() Returns value of specified key d.get('name')
keys() Returns all keys d.keys()
values() Returns all values d.values()
items() Returns key-value pairs d.items()
update() Updates with given dict d.update({'age': 25})
setdefault() Get or set default value d.setdefault('city','Delhi')
pop() Removes key and returns value d.pop('name')
popitem() Removes last item d.popitem()
clear() Empties the dictionary d.clear()
copy() Returns shallow copy new_d = d.copy()
fromkeys() New dict from keys dict.fromkeys(['a','b'], 0)

πŸ“— get() Method in Python Dictionary

Safely retrieve the value of a key from a dictionary. If the key is not found, it returns None or a specified default value.

Syntax : dictionary.get(key, default_value)


  student = {'name': 'Ravi', 'age': 21}

  # Existing key
  print(student.get('name'))       
              
  # Non-existing key without default
  print(student.get('grade')) 
              
  # Non-existing key with default
  print(student.get('grade', 'A'))              
            

πŸ“— keys() Method in Python Dictionary

The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.

Syntax : dictionary.keys()


  student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}

  print(student.keys())
            

πŸ“— values() Method in Python Dictionary

The values() method returns a view object. The view object contains the values of the dictionary, as a list.

Syntax : dictionary.values()


  student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}

  print(student.values())
            

πŸ“— items() Method in Python Dictionary

The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.

Syntax : dictionary.items()


  student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}

  print(student.items())
            

πŸ“— update() Method in Python Dictionary

The update() method allows you to add or update key-value pairs in the dictionary.

πŸ”‘ If the key already exists, its value will be updated.

πŸ”‘ If the key doesn't exist, the key-value pair is added.

Syntax : dictionary.update(iterable)


  student = {'name': 'Ravi', 'age': 21}

  # Adding a new key-value pair
  student.update({'grade': 'A'})
  print(student)
  
  # Updating an existing key-value pair
  student.update({'age': 22})
  print(student)
  
  # Update with another dictionary
  student.update({'city': 'Delhi', 'country': 'India'})
  print(student)            
            

πŸ“— setdefault() Method in Python Dictionary

The setdefault() method returns the value of a specified key.

If the key does not exist, it adds the key with a default value.

Syntax : dictionary.setdefault(key, default_value)


  student = {'name': 'Ravi', 'age': 21}

  # Existing key – returns current value
  print(student.setdefault('name'))

  # Non-existing key – adds with default None
  print(student.setdefault('course'))  

  # Non-existing key – adds with default value
  print(student.setdefault('grade', 'A'))  
  
  print(student)            
            

πŸ“— pop() Method in Python Dictionary

Removes the specified key and returns its value. If the key is not found, it raises a KeyError when default value is not given.

Syntax : dictionary.pop(key, default_value)


  student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}

  # Removing an existing key
  age = student.pop('age')
  print(age)     
  print(student)
  
  # Removing a non-existing key with default
  city = student.pop('city', 'Not Found')
  print(city)
  
  # Removing a non-existing key without default
  student.pop('city')  # ❌ This will raise KeyError              
            

πŸ“— popitem() Method in Python Dictionary

Removes and returns the last inserted key-value pair as a tuple.

Syntax : dictionary.popitem()


  student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}

  last_item = student.popitem()
  print(last_item)

  print(student)
  
  {}.popitem()  # ❌ KeyError
            

πŸ“— clear() Method in Python Dictionary

Removes all key-value pairs from the dictionary, making it empty.

Syntax : dictionary.clear()


  student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}

  student.clear()
  print(student)
            

πŸ“— copy() Method in Python Dictionary

Returns a shallow copy of the dictionary β€” a new dictionary with the same key-value pairs, but not the same reference.

Syntax : new_dict = original_dict.copy()


  student = {'name': 'Ravi', 'age': 21}

  new_student = student.copy()
  print(new_student)
  
  # Modifying the copy does not affect the original
  new_student['age'] = 30
  print(student)
  print(new_student)            
            

πŸ“— fromkeys() Method in Python Dictionary

Creates a new dictionary from a sequence of keys, each assigned the same value.

Syntax : dict.fromkeys(keys, value)


   
  # Using a list of keys
  keys = ['name', 'age', 'grade']
  default_dict = dict.fromkeys(keys)

  # Using a list of keys without specifying a value
  keys = ['name', 'age', 'grade']
  default_dict = dict.fromkeys(keys, 'Not Available')
            

🧠 Shallow Copy Warning in Python Dictionary

If the dictionary contains nested dictionaries, the nested parts still reference the original:

deepcopy() solves this by copying everything recursively, so changes in the copied dictionary don’t affect the original at all.

Syntax : from copy import deepcopy

Syntax : new_dict = deepcopy(original_dict)


  # Shallow Copy
  d1 = {'info': {'age': 21}}
  d2 = d1.copy()
  d2['info']['age'] = 30
  print(d1)  # {'info': {'age': 30}} ← Changed!  
  
 
  # deepcopy
  from copy import deepcopy

  original = {
      'name': 'Ravi',
      'marks': {'math': 90, 'science': 85}
  }

  copied = deepcopy(original)

  # Change the nested dictionary
  copied['marks']['math'] = 100

  print(original)
  # Output: {'name': 'Ravi', 'marks': {'math': 90, 'science': 85}}

  print(copied)
  # Output: {'name': 'Ravi', 'marks': {'math': 100, 'science': 85}}
            

Previous Next