Dictionary in Python
- Get link
- X
- Other Apps
Dictionary in Python
In Python, a dictionary is a built-in data structure that allows you to store key-value pairs. It is also known as a hash table or associative array. In this blog, we will explore how dictionaries work in Python, and how you can use them in your programs.
Creating a Dictionary
To create a dictionary in Python, you can use curly braces {}
or the dict()
constructor function. Here's an example:
# Using curly braces my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} # Using dict() constructor my_dict = dict(name='John', age=30, city='New York')
In the above code, we have created a dictionary with three key-value pairs, where the keys are name
, age
, and city
, and the values are John
, 30
, and New York
, respectively.
Accessing Dictionary Elements
To access a value in a dictionary, you can use the key inside square brackets or the get()
method. Here's an example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} # Accessing value using key print(my_dict['name']) # Output: John # Accessing value using get() print(my_dict.get('age')) # Output: 30
In the above code, we have accessed the values of the name
and age
keys using both square brackets and the get()
method.
Updating a Dictionary
To update the value of a key in a dictionary, you can simply assign a new value to it. Here's an example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} # Updating value of a key my_dict['age'] = 31 print(my_dict) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
In the above code, we have updated the value of the age
key to 31
.
Adding a New Key-Value Pair
To add a new key-value pair to a dictionary, you can simply assign a value to a new key that doesn't exist in the dictionary. Here's an example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} # Adding a new key-value pair my_dict['country'] = 'USA' print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
In the above code, we have added a new key-value pair, where the key is country
and the value is USA
.
Removing a Key-Value Pair
To remove a key-value pair from a dictionary, you can use the del
keyword or the pop()
method. Here's an example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} # Removing a key-value pair using del keyword del my_dict['city'] print(my_dict) # Output: {'name': 'John', 'age': 30} # Removing a key-value pair using pop() method age = my_dict.pop('age') print(my_dict) # Output: {'name': 'John'} print(age) # Output: 30
city
key-value pair using the del
keyword, and the age
key-value pair using the pop()
method.Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments