Advanced Python - IV

Dictionary in Python

A Dictionary in Python is a collection of key-value pairs. It stores data values like a map, where each unique key maps to a specific value. Unlike other data types that hold a single value per element, dictionaries hold pairs of values.

Example of Dictionary in Python

A dictionary holds data in a key:value format. This makes lookups, updates, and retrievals very efficient.

student = {101: 'Alice', 102: 'Bob', 103: 'Charlie'}
print(student)

Output:

{101: 'Alice', 102: 'Bob', 103: 'Charlie'}

Creating a Dictionary

In Python, you can create dictionaries by enclosing key-value pairs in curly braces {}, with keys and values separated by a colon : and pairs separated by commas.

Values in a dictionary can be of any data type and can be duplicated. However, keys must be unique and immutable (e.g. strings, numbers, tuples).

👀Note: Dictionary keys are case-sensitive. For instance, "Name" and "name" would be treated as two different keys.

# Dictionary with integer keys
employee = {1: 'John', 2: 'Emma', 3: 'Oliver'}
print("\nDictionary with integer keys:")
print(employee)

# Dictionary with mixed keys
info = {'Name': 'Sophia', 5: [10, 20, 30]}
print("\nDictionary with mixed keys:")
print(info)

Output:

Dictionary with integer keys:
{1: 'John', 2: 'Emma', 3: 'Oliver'}

Dictionary with mixed keys:
{'Name': 'Sophia', 5: [10, 20, 30]}

Creating a Dictionary with dict()

Dictionaries can also be created using Python’s built-in dict() function. You can pass key-value pairs as arguments or create an empty dictionary:

# Creating an empty dictionary
data = {}
print("Empty Dictionary:")
print(data)

# Using dict() method
fruits = dict({1: 'Apple', 2: 'Banana', 3: 'Cherry'})
print("\nDictionary using dict():")
print(fruits)

# Dictionary from list of tuples
cities = dict([(1, 'New York'), (2, 'Paris')])
print("\nDictionary created from list of pairs:")
print(cities)

Output:

Empty Dictionary:
{}

Dictionary using dict():
{1: 'Apple', 2: 'Banana', 3: 'Cherry'}

Dictionary created from list of pairs:
{1: 'New York', 2: 'Paris'}

Nested Dictionary

A dictionary can store another dictionary as a value, creating a nested dictionary.

# Nested Dictionary
company = {
    1: 'Google',
    2: 'Microsoft',
    3: {'A': 'Cloud', 'B': 'AI', 'C': 'Office'}
}

print(company)

Output:

{1: 'Google', 2: 'Microsoft', 3: {'A': 'Cloud', 'B': 'AI', 'C': 'Office'}}

Adding Elements to a Dictionary

You can add elements to a dictionary in several ways:

  • Direct assignment: dict[key] = value

  • Updating existing keys

  • Adding nested structures  

👀Note: If the key already exists, the value gets updated. Otherwise, a new key-value pair is created.
# Empty dictionary
book = {}
print("Empty Dictionary:")
print(book)

# Adding elements one by one
book['Title'] = 'Python Basics'
book['Author'] = 'Jane Doe'
book['Year'] = 2025
print("\nDictionary after adding elements:")
print(book)

# Adding a tuple as value
book['Chapters'] = (1, 2, 3, 4)
print("\nDictionary after adding a tuple as value:")
print(book)

# Updating a value
book['Author'] = 'John Smith'
print("\nDictionary after updating a key value:")
print(book)

# Adding a nested dictionary
book['Publisher'] = {'Name': 'TechBooks', 'City': 'London'}
print("\nDictionary after adding nested dictionary:")
print(book)

Output:

Empty Dictionary:
{}

Dictionary after adding elements:
{'Title': 'Python Basics', 'Author': 'Jane Doe', 'Year': 2025}

Dictionary after adding a tuple as value:
{'Title': 'Python Basics', 'Author': 'Jane Doe', 'Year': 2025, 'Chapters': (1, 2, 3, 4)}

Dictionary after updating a key value:
{'Title': 'Python Basics', 'Author': 'John Smith', 'Year': 2025, 'Chapters': (1, 2, 3, 4)}

Dictionary after adding nested dictionary:
{'Title': 'Python Basics', 'Author': 'John Smith', 'Year': 2025, 'Chapters': (1, 2, 3, 4), 'Publisher': {'Name': 'TechBooks', 'City': 'London'}}

Accessing Elements in a Dictionary

Access elements in a dictionary by referencing their keys:

profile = {1: 'Alice', 'Country': 'Canada', 3: 'Engineer'}

# Access using key
print("Accessing element using key:")
print(profile['Country'])

print("Accessing element using key:")
print(profile[1])

Output:

Accessing element using key:
Canada
Accessing element using key:
Alice

Accessing Elements with get()

The get() method also retrieves values safely. If the key does not exist, it returns None instead of throwing an error.

profile = {1: 'Alice', 'Country': 'Canada', 3: 'Engineer'}

print("Accessing element using get():")
print(profile.get(3))

# Access non-existing key safely
print(profile.get('Age'))

Output:

Accessing element using get():
Engineer
None

Accessing Elements in a Nested Dictionary

Use chained indexing to access values in nested dictionaries:

university = {
    'Department1': {101: 'Physics'},
    'Department2': {'Name': 'Chemistry'}
}

print(university['Department1'])
print(university['Department1'][101])
print(university['Department2']['Name'])

Output:

{101: 'Physics'}
Physics
Chemistry

Dictionary Methods

Here’s a quick summary of some common dictionary methods:

  • clear() – Removes all items

  • copy() – Returns a copy of the dictionary

  • get() – Returns the value for a given key

  • items() – Returns pairs of key-value tuples

  • keys() – Returns a list of keys

  • pop() – Removes an item with the specified key

  • popitem() – Removes the last inserted key-value pair

  • update() – Updates dictionary with new key-value pairs

  • values() – Returns a list of all values

✌Here’s a demonstration of these methods:

# Demo of dictionary methods
languages = {1: "Python", 2: "JavaScript", 3: "C++", 4: "Go"}

# copy()
langs_copy = languages.copy()
print(langs_copy)

# clear()
languages.clear()
print(languages)

# get()
print(langs_copy.get(2))

# items()
print(langs_copy.items())

# keys()
print(langs_copy.keys())

# pop()
langs_copy.pop(4)
print(langs_copy)

# popitem()
langs_copy.popitem()
print(langs_copy)

# update()
langs_copy.update({3: "Rust"})
print(langs_copy)

# values()
print(langs_copy.values())

Output:

{1: 'Python', 2: 'JavaScript', 3: 'C++', 4: 'Go'}
{}
JavaScript
dict_items([(1, 'Python'), (2, 'JavaScript'), (3, 'C++'), (4, 'Go')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'JavaScript', 3: 'C++'}
{1: 'Python', 2: 'JavaScript'}
{1: 'Python', 2: 'JavaScript', 3: 'Rust'}
dict_values(['Python', 'JavaScript', 'Rust'])

Popular Posts