Master Python Dictionary: 6 Essential Key-Value Operations

Table of Contents

A Python dictionary is an unordered, mutable, and indexed collection of key-value pairs. Each value is accessed using a unique key, making lookups super fast.

The main uses of the dictionary are:

				
					student = {
    "name": "Syaan",
    "age": 20,
    "course": "AI & ML",
}
				
			

Here:

  • “name”, “age”, and “course” are keys
  • “Syaan”, 20, and “AI & ML” are their corresponding values

You can think of a Python dictionary as a real-world dictionary: you look up a word (key) to find its meaning (value).

1. Creating a Dictionary

There are several ways to create a dictionary in Python.

1. Using Curly Braces {}:

This is the most common and direct way to create a dictionary. You define the dictionary structure by enclosing a comma-separated list of key: value pairs within curly braces.

          Example: person = {“name”: “James”, “city”: “New York”}

 

2. Using the dict() Constructor

The built-in dict() function is used to create a new dictionary. It can be called without arguments to create an empty dictionary, or it can accept keyword arguments or an iterable (like a list of tuples) to initialize the keys and values.

           Example: person = dict(name=”James”, city=”New York”)

 

3. From a List of Tuples

A dictionary can be constructed by passing a list (or any iterable) containing two-element tuples to the dict()  constructor. Each tuple must be structured as (key, value) where the first element becomes the key and the second becomes its corresponding value.

            Example: person = dict([(“name”, “James”), (“city”, “New York”)])

Consider a code example below

				
					# 1. Using Curly Braces 
user_profile = {
    "name": "Qubrica",
    "age": 40,
    "city": "Vinston City"
}
print(user_profile) 
#   {'name': 'Qubrica', 'age': 40, 'city': 'Vinston City'}


# 2. Using the dict() 
car_details = dict(brand="Tesla", model="Model 3", year=2022)
print(car_details)
#   {'brand': 'Tesla', 'model': 'Model 3', 'year': 2022}


# 3. From a List of Tuples
students_data = [
    ('id', 101), 
    ('grade', 'A'), 
    ('major', 'Science')
]  # Pass the list of tuples to the dict() constructor
student_dict = dict(students_data)
print(student_dict)
#   {'id': 101, 'grade': 'A', 'major': 'Science'}

				
			

2. Dictionary Access Methods

dictionary[key]:  Used to access the value of a specific key directly. If the key does not exist, Python will raise an error. 

 

dictionary.get(key, default): Returns the value of the specified key if it exists. If the key is not found, it returns the default value (or None if not provided). It mainly helps avoid runtime errors due to missing keys.

 

dictionary.keys(): Returns a view object that displays a list of all keys in the dictionary. The result updates automatically if the dictionary changes.

 

dictionary.values(): It provides a view object showing all the values currently stored in the dictionary. Like keys() it reflects any changes made to the dictionary. 

 

dictionary.items(): Returns a view object containing key-value pairs as tuples. Commonly used in loops to iterate through both keys and values.

 

for key in dictionary: When you loop directly through a dictionary, it iterates over its keys by default. You can then access the corresponding values using dictionary[key].

				
					student = {
    "name": "Kevin",
    "age": 19,
    "course": "Artificial Intelligence",
    "college": "Oxford"
}
# 1. Direct Access [key]
print("1. Student Name:", student["name"])

# 2. Safe Access using get()
print("2. Age:", student.get("age"))
print("2. Grade:", student.get("grade", "N/A")) # Uses default value

# 3. Accessing all keys
print("\n3. All Keys:", student.keys())

# 4. Accessing all values
print("4. All Values:", student.values())

# 5. (items())
print("\n5. Key-Value Pairs:")
for key, value in student.items():
    print(f"{key}: {value}")

# 6. Looping through keys by default
print("\n6. Looping through keys:")
for key in student:
    print(f"The value of '{key}' is '{student[key]}'")
    
    
#   1. Student Name: Kevin
#   2. Age: 19
#   2. Grade: N/A

#   3. All Keys: dict_keys(['name', 'age', 'course', 'college'])
#   4. All Values: dict_values(['Kevin', 19, 'Artificial Intelligence', 'Oxford'])

#   5. Key-Value Pairs:
#   name: Kevin
#   age: 19
#   course: Artificial Intelligence
#   college: Oxford

#   6. Looping through keys:
#   The value of 'name' is 'Kevin'
#   The value of 'age' is '19'
#   The value of 'course' is 'Artificial Intelligence'
#   The value of 'college' is 'Oxford'

				
			

3. Adding and updating elements in a Dictionary

1. Adding Dictionary Elements

A new key-value pair is added to the dictionary by assigning a value to a new (non-existent) key using bracket notation ([ ]).

Assignment TypeSyntaxHow it Adds
Bracket Assignmentdict["new key"]=new valueThe new key and value are instantly inserted into the dictionary.
.update()dict.update({"k1": v1, "k2": v2})Adds one or more new key-value pairs if the keys do not already exist.

4. Updating Dictionary Elements

The value of an existing key is changed by assigning a new value to that key using either the bracket notation ([ ]) or the powerful .update() method.

Update TypeSyntaxHow it Updates
Bracket Assignmentdict["existing_key"] = new_valueThe old value associated with the key is overwritten by the new value.
.update()dict.update({"key": new_value})Overwrites the value of the specified existing key(s) with the new value(s).
				
					student = {
    "name": "Caroline",
    "age": 20,
    "course": "Artificial Intelligence"
}
print(student)

# 1 Adding a key-value pair
student["grade"] = "A"
print("\nAfter Adding grade:")
print(student)

# 2 Updating value of an existing key
student["age"] = 21
print("\nAfter Updating age:")
print(student)

# 3 Adding multiple new items using update()
student.update({"college": "Stanford", "year": "3rd"})
print("\nAfter Adding Multiple Items using update():")
print(student)

# 4 Updating multiple existing keys using update()
student.update({"name": "John.", "grade": "A+"})
print("\nAfter Updating Multiple Keys using update():")
print(student)

#   {'name': 'Caroline', 'age': 20, 'course': 'Artificial Intelligence'}

#   After Adding grade:
#   {'name': 'Caroline', 'age': 20, 'course': 'Artificial Intelligence', 'grade': 'A'}

#   After Updating age:
#   {'name': 'Caroline', 'age': 21, 'course': 'Artificial Intelligence', 'grade': 'A'}

#   After Adding Multiple Items using update():
#   {'name': 'Caroline', 'age': 21, 'course': 'Artificial Intelligence', 'grade': 'A', 'college': 'Stanford', 'year': '3rd'}

#   After Updating Multiple Keys using update():
#   {'name': 'John.', 'age': 21, 'course': 'Artificial Intelligence', 'grade': 'A+', 'college': 'Stanford', 'year': '3rd'}

				
			

5. Deleting and Removing Dictionary Items

There are several methods to remove an element from the Dictionary. Let’s take a look at all of them.

MethodDefinitionAction
pop()Removes the item associated with a specific key provided as an argument, and returns the value of that removed item.dict.pop('key')
popitem()Removes and returns the last inserted key-value pair as a tuple. (Since Python 3.7, dictionaries maintain insertion order).dict.popitem()
delA Python keyword used to permanently delete a dictionary item based on its key (e.g., del dict['key']) or to delete the entire dictionary variable itself.del dict['key']
clear()Removes all elements from the dictionary, leaving it as an empty dictionary {}.dict.clear()
				
					student = {
    "name": "Caroline",
    "age": 20,
    "course": "Artificial Intelligence",
    "college": "Stanford",
    "grade": "A"
}
print(student)

# 1. pop(): 
print("\n1. Using pop('grade')")
removed_item = student.pop("grade")
print(f"Removed Value: {removed_item}")
print(f"Dictionary After Pop: {student}")

# 2. popitem():
print("\n 2. Using popitem() ")
last_removed = student.popitem()
print(f"Removed Pair (Tuple): {last_removed}")
print(f"Dictionary After Popitem: {student}")

# 3. del: 
print("\n3. Using del student['age']")
del student["age"]
print(f"Dictionary After Del: {student}")

# 4. clear():
print("\n4. Using clear()")
student.clear()
print(f" {student}")

#  {'name': 'Caroline', 'age': 20, 'course': 'Artificial Intelligence', 'college': 'Stanford', 'grade': 'A'}

#  1. Using pop('grade')
#  Removed Value: A
#  Dictionary After Pop: {'name': 'Caroline', 'age': 20, 'course': 'Artificial Intelligence', 'college': 'Stanford'}

#   2. Using popitem() 
#   Removed Pair (Tuple): ('college', 'Stanford')
#   Dictionary After Popitem: {'name': 'Caroline', 'age': 20, 'course': 'Artificial Intelligence'}

#   3. Using del student['age']
#   Dictionary After Del: {'name': 'Caroline', 'course': 'Artificial Intelligence'}

#   4. Using clear() 
#   {}


				
			

6. Looping Through a Dictionary

Looping through a dictionary is the process of iterating over its contents to access its keys, values or both one pair at a time.

There are several methods to loop through a dictionary. Let’s take a look at it one by one

1. Looping through keys

This is the default way a for loop iterates over a dictionary. The loop variable successively takes on the value of each key in the dictionary. You can then use the key to access the corresponding value.

 

2. Looping through values

This method uses the dictionary’s built-in .values()  view object. It allows you to iterate directly over all the values stored in the dictionary without needing to access or deal with the keys.

 

3. Looping through key-value pairs using items()

This is the most common and efficient way to access both components of the dictionary simultaneously. The .items view object returns each item as a two-element tuple (key, value) which is typically unpacked into two loop variables.

 

4. Looping using keys() explicitly

This method uses the dictionary’s built-in .keys() view object. It explicitly returns a view of all the keys, making the intent of the loop clear, although it behaves identically to a simple for key in dictionary: loop

				
					student = {
    "name": "Caroline",
    "age": 20,
    "course": "Artificial Intelligence",
    "college": "Stanford"
}
print("Dictionary:", student)

# 1 Looping through keys
print("\nLooping through keys:")
for key in student:
    print(key)

# 2 Looping through values
print("\nLooping through values:")
for value in student.values():
    print(value)

# 3 Looping through key-value pairs using items()
print("\nLooping through key-value pairs:")
for key, value in student.items():
    print(f"{key}: {value}")

# 4️ Looping using keys() explicitly
print("\nLooping using keys():")
for key in student.keys():
    print(f"{key} -> {student[key]}")

#  Looping through keys:
#  name
#  age
#  course
#  college

#  Looping through values:
#  Caroline
#  20
#  Artificial Intelligence
#  Stanford

#  Looping through key-value pairs:
#  name: Caroline
#  age: 20
#  course: Artificial Intelligence
#  college: Stanford

#  Looping using keys():
#  name -> Caroline
#  age -> 20
#  course -> Artificial Intelligence
#  college -> Stanford


				
			

Nested Dictionary

A nested dictionary is a dictionary where the value associated with a key is another dictionary. This structure is used to represent hierarchical or complex data allowing you to organise information into logical levels.

				
					students = {
    "S001": {
        "name": "Caroline",
        "age": 20,
        "course": "AI & ML"
    },
    "S002": {
        "name": "David",
        "age": 19,
        "course": "Data Science"
    }
}
# Accessing nested values
print(students["S001"]["name"])          #  Caroline
print(students["S002"]["course"])        #  Data Science

				
			

FAQ (Frequently Asked Questions)

1) How to iterate through a dictionary?

We can iterate through a dictionary by using a for loop. We can access any of its key-value pairs. Consider an example below

student_scores = {
“Math”: 95,
“Science”: 88,
“History”: 75
}
for subject, score in student_scores.items():
print(f”{subject}: {score}%”)

Using the above code you can access the subject and the code.

 

2) How to append to a dictionary in Python?

The most common way to append a dictionary is the direct assignment of the values. Add a key-value pair using assignment:

my_dict[“new_key”] = “new_value”

 

3) Is a dictionary value mutable or immutable in Python?

Dictionary values can be both. You can store mutable (lists, other dictionaries) or immutable (int, string, tuple) values.

 

4) How to initialize a dictionary in Python?

There are several ways to initialize a dictionary. Take a look at the few examples below

my_dict = {}

my_dict = {“name”: “Rakshath”, “age”: 20}

my_dict = dict(name=”Rakshath”, age=20)

 

5) How to print a dictionary in Python?

To print a dioctionary we can use the print() statement

print(my_dict)

 

6) How to convert a list to a dictionary in Python?

Consider a few examples below to convert a list into a dictionary.

If the list contains pairs:

my_list = [(“a”, 1), (“b”, 2)]

my_dict = dict(my_list)

Or using indexes:

my_dict = {i: my_list[i] for i in range(len(my_list))}

 

7) How to merge two dictionaries in Python?

To merge two dictionaries use update() or the merge operator:

dict1.update(dict2)

# or

merged = {**dict1, **dict2}

 

8) How to check if a key exists in a dictionary?

To check if the key exists use the in operator:

if “name” in my_dict:

    print(“Key exists”)

 

9) How to sort a dictionary by key?

We can use sorted() and dictionary comprehension:

sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}

 

10) How to sort a dictionary by value?

We can Sort by using sorted() with a key function:

sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda x: x[1])}