Python From Beginner to Advanced

0% completed

Previous
Next
Python - Dictionary Basics

A dictionary in Python is a data structure that stores key-value pairs, where each key is unique and maps to a corresponding value. This makes dictionaries ideal for fast data retrieval without relying on indexing positions like lists or tuples. Instead, data is accessed using keys, which act as identifiers.

Dictionaries are commonly used in data analysis, caching, configurations, and database-like storage where quick lookups are required. Unlike lists, dictionaries are unordered collections in Python versions before 3.7. However, starting from Python 3.7+, dictionaries maintain insertion order, meaning elements appear in the same order they were added.

Dictionaries also provide dynamic sizing, meaning they can grow or shrink as needed. The length of a dictionary can be determined using the len() function, which returns the total number of key-value pairs.

Image

1. Defining a Dictionary

A dictionary is created by placing key-value pairs inside curly braces {}, where:

  • Keys must be unique and immutable (strings, numbers, or tuples).
  • Values can be of any data type, including lists, tuples, or even other dictionaries.

Example 1: Creating a Simple Dictionary

Python3
Python3

. . . .

Explanation

  • "Alice", "Bob", and "Eve" are keys, while 22, 25, and 19 are their respective values.
  • The dictionary is printed, displaying its key-value pairs.
  • The order of elements remains the same in Python 3.7 and later.

2. Dictionary Length

The number of key-value pairs in a dictionary can be determined using the len() function.

Example 2: Finding the Length of a Dictionary

Python3
Python3

. . . .

Explanation

  • len(student_ages) returns 3 because the dictionary contains three key-value pairs.

3. Dictionary with Different Data Types

Dictionaries allow keys to be numbers or strings, while values can be of any type, including lists, tuples, or nested dictionaries.

Example 3: Using Different Data Types in a Dictionary

Python3
Python3

. . . .

Explanation

  • "name" and "age" store string and integer values.
  • "hobbies" stores a list as a value.
  • "married" holds a boolean value.
  • "address" contains a nested dictionary.

Dictionaries are highly flexible, making them suitable for structured data storage.

4. Dictionary Keys Must Be Immutable

Dictionary keys must be immutable, meaning they cannot be lists, other dictionaries, or any mutable object.

Example 4: Valid and Invalid Dictionary Keys

Python3
Python3

. . . .

Explanation

  • Valid keys include strings, integers, and tuples, as they are immutable.
  • Invalid keys, such as a list, will cause a TypeError because lists are mutable.

Overall, Dictionaries provide efficient storage and retrieval of data, making them one of the most powerful built-in data structures in Python.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next