Python

Python Dictionaries

Python Dictionaries are one of the most powerful and flexible built-in data types in Python. They provide a way to store data in key-value pairs, making it easy to access, update, and manipulate structured information efficiently. Dictionaries are widely used in real-world applications, from configuration settings to storing user data and mapping relationships.

What are Python Dictionaries?

A Python Dictionary is an unordered, mutable collection of items. Each item is a pair of a key and its corresponding value. Keys must be unique and immutable (such as strings, numbers, or tuples), while values can be of any data type.

Basic Syntax of Python Dictionaries

# Creating a dictionary person = { "name": "Alice", "age": 30, "city": "New York" } print(person["name"]) # Output: Alice

In this example, the dictionary person contains three key-value pairs, and you can retrieve values by referencing their keys.

Key Features of Python Dictionaries

  • Unordered: Items are not stored in any particular order (until Python 3.7; from 3.7 onwards, dictionaries maintain insertion order).
  • Mutable: You can add, change, or remove items.
  • Dynamic: Size and contents can be modified at runtime.
  • Efficient Lookup: Accessing a value by key is very fast, typically O(1) time complexity.

Creating Python Dictionaries

Different Ways to Create Dictionaries

# Using curly braces d1 = {"a": 1, "b": 2} # Using dict() constructor d2 = dict(x=10, y=20) # Using a list of tuples d3 = dict([("name", "Bob"), ("age", 25)]) # Empty dictionary empty = {}

Accessing and Modifying Dictionary Elements

person = {"name": "Tom", "age": 22} # Accessing value print(person["age"]) # Output: 22 # Modifying value person["age"] = 23 # Adding a new key-value pair person["city"] = "London"

Common Dictionary Methods

Method Description Example
keys() Returns all keys person.keys()
values() Returns all values person.values()
items() Returns key-value pairs person.items()
get() Returns value for key, or default person.get("name")
update() Updates dictionary with key-value pairs person.update({"age": 35})
pop() Removes item with given key person.pop("city")

Looping Through Python Dictionaries

user = {"name": "Eva", "role": "admin", "status": "active"} # Loop through keys for key in user: print(key) # Loop through values for value in user.values(): print(value) # Loop through key-value pairs for key, value in user.items(): print(key, ":", value)

Nested Python Dictionaries

You can nest dictionaries within dictionaries for complex data structures.

students = { "student1": {"name": "Alice", "age": 21}, "student2": {"name": "Bob", "age": 22} } print(students["student1"]["name"]) # Output: Alice

Why Use Python Dictionaries?

  • To store data in key-value pairs for quick access.
  • To represent structured information (e.g., user profiles, configurations).
  • To model real-world relationships like ID to name, product code to description.
  • To build JSON-like structures for APIs and databases.

Real-World Applications of Python Dictionaries

  • Storing user data in web applications
  • Representing JSON data
  • Building frequency counters and word count applications
  • Maintaining application settings or environment variables
  • Mapping keys to values in lookup tables

Python Dictionaries vs Lists

Feature Dictionaries Lists
Storage Key-value pairs Sequential items
Access Accessed by key Accessed by index
Order (Python 3.7+) Maintains insertion order Maintains insertion order
Use Case Lookup operations Ordered data storage

Conclusion

Python Dictionaries are an indispensable part of Python programming. Their flexibility and efficiency in handling key-value data make them ideal for a wide variety of tasks. Mastering dictionaries will improve your ability to write clean, fast, and functional Python code that can handle structured data with ease.

line

Copyrights © 2024 letsupdateskills All rights reserved