Dictionaries in Python can be created in several ways. Here are some common methods:
-
Using curly braces
{}:my_dict = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } -
Using the
dict()constructor:my_dict = dict(key1='value1', key2='value2', key3='value3') -
Using a list of tuples:
my_dict = dict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]) -
Using dictionary comprehension:
my_dict = {x: x**2 for x in range(5)} # Creates a dictionary with keys 0-4 and values as their squares -
From another dictionary:
original_dict = {'key1': 'value1', 'key2': 'value2'} new_dict = dict(original_dict) # Creates a copy of the original dictionary
You can access values in a dictionary using their keys, and you can also add or update key-value pairs easily.
