Python Dictionary
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

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.

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.

<class 'dict'>

Using the dict() Constructor

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

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

Python Collection Data 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. If the key does not exist, this method raises a KeyError.

Developer

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.

Developer

Get All Dictionary Keys

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

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

The keys view reflects changes made to the dictionary 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.

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

Updating an existing value dynamically updates the view:

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

Adding a new key-value pair also updates the view:

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

Get All Dictionary Items

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

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

Modifying an existing item:

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

Adding a new item:

dict_items([('id', 101), ('name', 'Ravi'), ('role', 'Developer')]) dict_items([('id', 101), ('name', 'Ravi'), ('role', 'Developer'), ('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.

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

{'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.

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

Example: Update multiple values at once:

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

Key Difference: Direct assignment updates only one key at a time, while update() can modify or insert multiple items in a single statement.

Adding Items to a Dictionary

Add an Item Using a New Key

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

Add Items Using the update() Method

{'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

1. Removing an Item Using pop()

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

2. Removing the Last Inserted Item Using popitem()

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

3. Removing an Item 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)

username followers active

2. Looping Through Values Using Keys

max_dev 1200 True

3. Looping Through Values Using values()

max_dev 1200 True

4. Looping Through Keys Using keys()

username followers active

5. Looping Through Keys and Values 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. To create an independent copy, Python provides safe methods.

Method 1: Using the copy() Method

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

Method 2: Using the dict() Constructor

{'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.

Example 1: Creating a Nested Dictionary Directly

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

Example 2: Combining Multiple Dictionaries into One

{'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.

Data Science Guide

Looping Through Nested Dictionaries

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

book1 title: Python Basics price: 499 book2 title: Data Science Guide price: 899 book3 title: Web Development price: 699
Our website uses cookies to enhance your experience. Learn More
Accept !