Python Dictionary

Python Dictionary

Kishore V


Python Dictionary

A dictionary in Python is used to store data in the form of key–value pairs. Each key acts as a unique identifier for its associated value.

A dictionary has the following characteristics:

  • Ordered (from Python 3.7 onwards)
  • Changeable (mutable)
  • Does not allow duplicate keys

Creating a Dictionary

Dictionaries are created using curly braces {}, with each item written as key: value.

Example: Create and display a dictionary

{'name': 'Amit', 'course': 'Python', 'duration': 6}

Dictionary Items

Each item in a dictionary consists of a key and a value. You can access a value by referring to its key name.

Example: Access a specific value

Python

Ordered vs Unordered Dictionaries

  • From Python 3.7 and later, dictionaries maintain the order in which items are inserted.
  • In Python 3.6 and earlier, dictionaries do not guarantee order.

Ordered means items stay in the same sequence.

Unordered means items do not have a fixed position and cannot be accessed using an index.

Changeable Nature of Dictionaries

Dictionaries allow you to add, modify, or remove items after creation.

Example: Modify a value

{'name': 'Amit', 'course': 'Python', 'duration': 8}

Duplicate Keys Not Allowed

A dictionary cannot contain two items with the same key. If a duplicate key is used, the latest value replaces the old one.

Example: Duplicate key behavior

{'brand': 'Tesla', 'year': 2023}

Dictionary Length

To find the number of key–value pairs in a dictionary, use the len() function.

Example: Get dictionary length

3

Dictionary Values and Data Types

Dictionary values can store any data type, including strings, numbers, booleans, and lists.

Example: Multiple data types in a dictionary

{'name': 'Laptop', 'price': 65000, 'available': True, 'features': ['SSD', '8GB RAM', 'i5 Processor']}

Dictionary Data Type

From Python’s perspective, dictionaries belong to the dict data type.

Example: Check dictionary type

<class 'dict'>

Using the dict() Constructor

You can also create a dictionary using the built-in dict() function.

Example: Create dictionary using dict()

{'username': 'max123', 'followers': 1200, 'verified': False}

Python Collection Data Types

Python provides four built-in collection types:

  • List – Ordered, changeable, allows duplicate values
  • Tuple – Ordered, unchangeable, allows duplicate values
  • Set – Unordered, unchangeable*, does not allow duplicates
  • Dictionary – Ordered**, changeable, does not allow duplicate keys

Accessing Dictionary Items in Python

You can retrieve values from a dictionary by referring to their key names. Python provides multiple ways to access dictionary data safely and efficiently.

Access Values Using Square Brackets

The most common way to access a dictionary value is by using the key inside square brackets.

Example: Access a value using a key

Developer

If the key does not exist, this method raises a KeyError.

Access Values Using the get() Method

The get() method also retrieves values using keys, but it is safer because it does not throw an error if the key is missing.

Example: Access value using get()

Developer

Get All Dictionary Keys

The keys() method returns a view object containing all the keys in the dictionary.

Example: Retrieve all keys

dict_keys(['id', 'name', 'role'])

Keys View Updates Automatically

The keys view reflects changes made to the dictionary.

Example: View updates automatically

dict_keys(['id', 'name', 'role']) dict_keys(['id', 'name', 'role', 'salary'])

Get All Dictionary Values

The values() method returns a view of all the values stored in the dictionary.

Example: Retrieve all values

dict_values([101, 'Ravi', 'Developer'])

Values View Reflects Changes

Example: Updating an existing value and adding a new key-value pair

dict_values([101, 'Ravi', 'Developer']) dict_values([101, 'Ravi', 'Senior Developer']) dict_values([101, 'Ravi', 'Senior Developer', 5])

Get All Dictionary Items

The items() method returns a view containing key–value pairs as tuples.

Example: Retrieve key–value pairs

dict_items([('id', 101), ('name', 'Ravi'), ('role', 'Developer')])

Items View Updates Automatically

Example: Modify and add items

dict_items([('id', 101), ('name', 'Ravi'), ('role', 'Developer')]) dict_items([('id', 101), ('name', 'Ravi'), ('role', 'Team Lead')]) dict_items([('id', 101), ('name', 'Ravi'), ('role', 'Team Lead'), ('location', 'Bangalore')])

Check If a Key Exists in a Dictionary

You can use the in keyword to verify whether a specific key exists in a dictionary.

Example: Check for a key

Yes, 'role' exists in the employee dictionary

Changing Values in a Dictionary

In Python, dictionary values can be modified easily by referencing their key names. Since dictionaries are mutable, you can update existing entries after the dictionary is created.

Change a Value Using the Key

You can directly assign a new value to a key using square brackets.

Example: Modify an existing value

{'name': 'Smartphone', 'brand': 'TechOne', 'price': 15000}

Updating Dictionary Using update()

The update() method allows you to change or add multiple key–value pairs at once. The argument passed must be either: Another dictionary, or an iterable containing key–value pairs.

Example: Update a single value using update()

{'name': 'Smartphone', 'brand': 'TechOne', 'price': 16500}

Example: Update multiple values at once

{'name': 'Smartphone', 'brand': 'TechOne', 'price': 16500, 'stock': 40}

Key Difference Between Direct Assignment and update()

  • Direct assignment updates only one key at a time.
  • update() can modify or insert multiple items in a single statement.

Adding Items to a Dictionary

In Python, you can add new items to a dictionary by assigning a value to a new key. Since dictionaries are mutable, new key–value pairs can be inserted at any time.

Add an Item Using a New Key

You can directly add an item by specifying a new key and assigning a value to it.

Example: Add a new key–value pair

{'username': 'max_dev', 'followers': 850, 'verified': True, 'bio': 'Python enthusiast'}

Add Items Using the update() Method

The update() method can be used to add one or more items to a dictionary.

  • If the key already exists, its value is updated.
  • If the key does not exist, a new item is added.

Example: Add an item using update()

{'username': 'max_dev', 'followers': 850, 'verified': True, 'location': 'India'}

Example: Add multiple items at once

{'username': 'max_dev', 'followers': 850, 'verified': True, 'skills': ['Python', 'Django'], 'active': True}

Removing Items from a Dictionary

Python provides multiple ways to remove items from a dictionary, depending on whether you want to delete a specific key, the last inserted item, or all items.

1. Removing an Item Using pop()

The pop() method removes the item with the specified key and returns its value.

Example: Remove the "author" key

{'title': '1984', 'year': 1949}

2. Removing the Last Inserted Item Using popitem()

The popitem() method removes the last inserted key-value pair. (In Python versions earlier than 3.7, a random item is removed instead).

Example: Remove using popitem()

{'name': 'Aarav', 'age': 20}

3. Removing an Item Using del

The del keyword removes an item by referencing its key name.

Example: Remove using del

{'id': 101, 'name': 'Riya'}

Looping Through a Dictionary

You can iterate over a dictionary using a for loop. By default, looping through a dictionary returns its keys, but Python also provides built-in methods to access values and key–value pairs.

1. Looping Through Keys (Default Behavior)

When you loop directly over a dictionary, Python returns each key one by one.

Example: Print all keys

username followers active

2. Looping Through Values Using Keys

You can access the values by using each key inside the loop.

Example: Loop through values

max_dev 1200 True

3. Looping Through Values Using values()

The values() method returns all values from the dictionary.

Example: Using values()

max_dev 1200 True

4. Looping Through Keys Using keys()

The keys() method explicitly returns all keys of the dictionary.

Example: Using keys()

username followers active

5. Looping Through Keys and Values Using items()

The items() method returns both keys and values as pairs, making it easy to work with both.

Example: Using items()

username : max_dev followers : 1200 active : True

Copying a Dictionary in Python

In Python, assigning one dictionary to another using dict2 = dict1 does not create a new dictionary. Instead, both variables point to the same object in memory, so any change made to one will affect the other.

To create an independent copy of a dictionary, Python provides safe and simple methods.

Method 1: Using the copy() Method

The copy() method creates a shallow copy of the dictionary, meaning a new dictionary object is created with the same key–value pairs.

Example: Copy a dictionary using copy()

{'name': 'Aarav', 'age': 20, 'course': 'Computer Science'}

Method 2: Using the dict() Constructor

Another common way to copy a dictionary is by passing the original dictionary to the dict() function. This also creates a new dictionary object.

Example: Copy a dictionary using dict()

{'id': 101, 'name': 'Laptop', 'price': 55000}

Nested Dictionaries in Python

A nested dictionary is a dictionary that stores one or more dictionaries as its values. This structure is useful when you need to represent grouped or hierarchical data, such as users with profiles, students with details, or products with specifications.

Example 1: Creating a Nested Dictionary Directly

Below is an example where a single dictionary contains multiple dictionaries inside it:

{'emp1': {'name': 'Ravi', 'department': 'HR'}, 'emp2': {'name': 'Anita', 'department': 'Finance'}, 'emp3': {'name': 'Kunal', 'department': 'IT'}}

Example 2: Combining Multiple Dictionaries into One

You can also create separate dictionaries first and then store them inside a new dictionary:

{'book1': {'title': 'Python Basics', 'price': 499}, 'book2': {'title': 'Data Science Guide', 'price': 899}, 'book3': {'title': 'Web Development', 'price': 699}}

Accessing Values from a Nested Dictionary

To access data inside a nested dictionary, use multiple keys—starting from the outer dictionary and moving inward.

Example: Print the title of book2

Data Science Guide

Looping Through Nested Dictionaries

You can loop through a nested dictionary using the items() method to access both keys and values.

Example: Loop through all books and their details

book1 title: Python Basics price: 499 book2 title: Data Science Guide price: 899

Our website uses cookies to enhance your experience. Learn More
Accept !