How to create a dictionary in Python?
Table of Contents
Introduction
A dictionary in Python is an unordered collection of key-value pairs. Dictionaries are mutable, allowing for dynamic modification. They are commonly used to store data that needs to be accessed via unique keys.
Creating a Dictionary
1. Using Curly Braces {}
You can create a dictionary by enclosing key-value pairs in curly braces. Each key-value pair is separated by a colon, and pairs are separated by commas.
Example:
2. Using the dict()
Constructor
You can also create a dictionary using the dict()
constructor. This method is particularly useful when creating a dictionary from a list of tuples.
Example:
3. Creating a Dictionary from a List of Tuples
If you have a list of tuples where each tuple contains a key-value pair, you can use the dict()
constructor to create a dictionary.
Example:
4. Using Dictionary Comprehension
Dictionary comprehension allows for the creation of dictionaries using a concise and readable syntax. This method is particularly useful for creating dictionaries based on existing data.
Example:
5. Creating an Empty Dictionary
You can create an empty dictionary and then add key-value pairs to it as needed.
Example:
Practical Examples
Example 1: Creating a Dictionary with Mixed Data Types
Example 2: Using a Dictionary to Store User Information
Conclusion
Creating a dictionary in Python can be done using several methods, including curly braces, the dict()
constructor, a list of tuples, dictionary comprehension, and starting with an empty dictionary. Each method has its use cases, and choosing the right one depends on your specific needs.