Python is a versatile programming language that comes with a wide range of built-in data structures. These data structures allow programmers to efficiently store and manipulate data. One commonly used data structure in Python is the dictionary.
What is a Dictionary?
A dictionary is an unordered collection of key-value pairs. Each key-value pair in a dictionary is separated by a colon (:), and the pairs are enclosed in curly braces {}. Dictionaries are also sometimes referred to as associative arrays or hash maps.
How to Create a Dictionary
To create a dictionary in Python, you can use the following syntax:
- Create an empty dictionary:
my_dict = {}
- Create a dictionary with initial values:
my_dict = {'key1': value1, 'key2': value2}
Note that the keys in a dictionary must be unique, but the values can be duplicated.
Accessing Values in a Dictionary
You can access the values stored in a dictionary by using their corresponding keys. For example:
# Create a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
# Access values
name = my_dict['name']
age = my_dict['age']
city = my_dict['city']
# Print values
print(name) # Output: John
print(age) # Output: 25
print(city) # Output: New York
Built-in Functions for Dictionaries
Python provides several built-in functions that can be used to perform various operations on dictionaries:
- len(): Returns the number of key-value pairs in a dictionary.
- keys(): Returns a list of all the keys in a dictionary.
- values(): Returns a list of all the values in a dictionary.
- items(): Returns a list of all the key-value pairs in a dictionary as tuples.
# Using built-in functions
print(len(my_dict)) # Output: 3
print(my_dict.keys()) # Output: [‘name’, ‘age’, ‘city’]
print(my_dict.values()) # Output: [‘John’, 25, ‘New York’]
print(my_dict.items()) # Output: [(‘name’, ‘John’), (‘age’, 25), (‘city’, ‘New York’)]
Modifying and Deleting Dictionary Elements
Dictionaries are mutable, which means you can modify their elements by assigning new values to specific keys. You can also delete elements from a dictionary using the del
keyword.
# Modifying elements
my_dict[‘age’] = 26
my_dict[‘city’] = ‘San Francisco’
# Deleting elements
del my_dict[‘name’]
# Print modified dictionary
print(my_dict) # Output: {‘age’: 26, ‘city’: ‘San Francisco’}
Conclusion
In conclusion, a dictionary is indeed a built-in data structure in Python. It allows you to store and retrieve data efficiently using key-value pairs.
Dictionaries are versatile and widely used in various programming scenarios. By understanding how dictionaries work and utilizing their built-in functions, you can leverage the power of this data structure to write more efficient and organized Python code.