Dictionaries in Python

Dictionaries in Python are unordered collections of key-value pairs. They are used to store data in a structured way, allowing fast retrieval based on keys.

Creating Dictionaries

Dictionaries are created using curly braces {}, with each key-value pair separated by a colon :.

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

Accessing Elements

Elements in a dictionary can be accessed by their keys.

name = my_dict['name']
age = my_dict.get('age')

Modifying and Adding Elements

You can modify the value associated with a key or add new key-value pairs to a dictionary.

my_dict['age'] = 35
my_dict['gender'] = 'Male'