A dictionary in Python is an unordered collection of key-value pairs. It is a mutable, indexed, and iterable data structure that is commonly used to store and retrieve data. The keys in a dictionary must be unique and immutable (strings, integers, tuples) while the values can be of any data type (strings, integers, lists, sets, other dictionaries, etc.). It could be create by my_dict = {"name": "John", "age": 25, "city": "New York"}
Here is some basic operations for Python dictionary
Creating a dictionary
my_dict = {"name": "John", "age": 25, "city": "New York"}
Accessing values using keys
print(my_dict["name"]) print(my_dict["age"])
John
25
Adding a new key-value pair
my_dict["country"] = "USA" print(my_dict)
{"name": "John", "age": 25, "city": "New York", "country": "USA"}
Removing and Updating
del my_dict["city"] my_dict["age"] = 26
Checking if a key exists in a dictionary
if"name"in my_dict: print("Name is present") else: print("Name is not present")
# Iterating through a dictionary for key, value in my_dict.items(): print(key, value)