Dictionaries
Dictionaries in Python are a type of data structure that store data in the form of key-value pairs. Each key-value pair is also known as an item. Dictionaries are useful for storing and retrieving data when the data can be referenced by a unique key.
Creating a Dictionary:
To create a dictionary, you can use curly braces ({}) or the built-in dict() function. Each item in the dictionary is separated by a comma, with the key and value separated by a colon (:).
Example:
# Using curly braces
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# Using dict() function
my_dict = dict(name='John', age=25, city='New York')
Accessing Values in a Dictionary:
To access a value in a dictionary, you can use the square bracket notation with the key of the item you want to access.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(my_dict['name']) # Output: John
print(my_dict['age']) # Output: 25
print(my_dict['city']) # Output: New York
If the key you are trying to access is not present in the dictionary, a KeyError will be raised. To avoid this, you can use the get()
method, which returns None
if the key is not present.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(my_dict.get('name')) # Output: John
print(my_dict.get('salary')) # Output: None
Modifying a Dictionary:
To modify a value in a dictionary, you can use the square bracket notation with the key of the item you want to modify and then assign a new value to it.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict['age'] = 26
print(my_dict) # Output: {'name': 'John', 'age': 26, 'city': 'New York'}
To add a new key-value pair to the dictionary, you can use the square bracket notation with the new key and then assign a new value to it.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
my_dict['salary'] = 50000
print(my_dict) # Output: {'name': 'John', 'age': 25, 'city': 'New York', 'salary': 50000}
To delete an item from a dictionary, you can use the del
keyword followed by the key of the item you want to delete.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
del my_dict['age']
print(my_dict) # Output: {'name': 'John', 'city': 'New York'}
You can also use the pop()
method to remove an item from the dictionary and return its value.
Example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
age = my_dict.pop('age')
print(age) # Output: 25
print(my_dict) # Output: {'name': 'John', 'city': 'New York'}
That’s the basics of dictionaries in Python. They are a powerful and flexible data structure that can be used in many different ways to store and retrieve data.
for the Next step Click here