Creating a new dictionary in Python
A dictionary in Python is a collection of key-value pairs. You can easily create one using curly braces {} or the dict() function, and it allows you to store and retrieve values efficiently using unique keys.
To create a new dictionary in Python, you can use two common approaches:
1. Using Curly Braces {}:
The simplest way to create a dictionary is by using curly braces {} and separating key-value pairs with a colon :. Multiple pairs are separated by commas.
Example:
my_dict = {"name": "John", "age": 25, "city": "New York"}
print(my_dict)
In this example, "name", "age", and "city" are the keys, and their corresponding values are "John", 25, and "New York".
2. Using the dict() Constructor:
The dict() function is another way to create a dictionary. It is particularly useful when you want to create dictionaries from sequences of key-value pairs or when the keys are strings.
Example:
my_dict = dict(name="John", age=25, city="New York")
print(my_dict)
Here, we use the dict() constructor to create the dictionary with the same key-value pairs.
Points to Note:
- Keys must be unique: A dictionary cannot have two identical keys. If you try to add a duplicate key, it will overwrite the existing value for that key.
- Values can be of any data type: While keys must be immutable (strings, numbers, tuples), values can be of any data type, such as lists, tuples, or even other dictionaries.
- Dictionaries are unordered: Although Python dictionaries maintain insertion order (from Python 3.7+), they are still considered unordered collections when accessed via methods like iteration.