Python Dictionaries
Python dictionaries are a powerful data structure used to store key-value pairs. They are mutable, unordered, and can contain any number of key-value pairs. They are similar to lists, but unlike lists, dictionaries use keys to access the values, rather than using an index. The keys in a dictionary must be unique and immutable, while the values can be of any data type. Dictionaries are denoted by curly braces {} and use a colon : to separate the key and value.
1dict_literal = {'name': 'William', 'age': 22}
Dictionaries are often used to store data in a structured way, such as a collection of user information or a database of products. The keys in a dictionary must be unique and immutable, while the values can be of any data type.
Creating a Dictionary
To create a dictionary, you can use the following syntax:
1# Empty dictionary 2my_dict = {} 3# Dictionary with initial values 4my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
You can also create a dictionary using the dict() constructor
1# Using dict() constructor 2my_dict = dict(key1='value1', key2='value2', key3='value3')
Python dictionary comprehension
In addition, you can use dictionary comprehension to create a new dictionary by applying an operation to each key-value pair of an existing dictionary.
1numbers = {'a': 1, 'b': 2, 'c': 3} 2squared_numbers = {k: v**2 for k, v in numbers.items()} 3print(squared_numbers) # Output: {'a': 1, 'b': 4, 'c': 9}
Accessing Values
To access a value in a dictionary, you can use the key as the index:
1# Accessing values 2my_dict = {'name': 'William', 'age': 25, 'city': 'New York'} 3print(my_dict['name']) # Output: William
Python also provides a method called get()
which allows you to access the value of a key without raising an error if the key is not found in the dictionary. This can be useful when you're working with dictionaries that may contain keys that don't always exist.
You can also use the get() method to retrieve a value:
1# Using get() method 2print(my_dict.get('age')) # Output: 25
1user = {'name': 'William', 'age': 22} 2print(user.get('gender', None)) # Output: None
If a key is not present in the dictionary, the get() method returns None.
Updating Values
To update the value of a key in a dictionary, you can simply assign a new value to the key:
1# Updating values 2my_dict['age'] = 22 3print(my_dict) # Output: {'name': 'William', 'age': 22, 'city': 'New York'}
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:
1# Adding a new key-value pair 2my_dict['gender'] = 'Male' 3print(my_dict) # Output: {'name': 'William', 'age': 22, 'city': 'New York', 'gender': 'Male'}
Removing a Key-Value Pair
To remove a key-value pair from a dictionary, you can use the del keyword:
1# Removing a key-value pair 2del my_dict['city'] 3print(my_dict) # Output: {'name': 'William', 'age': 22, 'gender': 'Male'}
Dictionary Methods
Python dictionaries have several useful methods that can be used to manipulate and work with dictionaries. Some of the most common methods include:
keys():
Returns a list of all the keys in the dictionaryvalues():
Returns a list of all the values in the dictionaryitems():
Returns a list of tuples containing the key-value pairs in the dictionaryclear():
Removes all the key-value pairs from the dictionarycopy():
Returns a copy of the dictionary
1# Dictionary methods 2print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'gender']) 3print(my_dict.values()) # Output: dict_values(['William', 22, 'Male']) 4print(my_dict.items()) # Output: dict_items([('name', 'William'), ('age', 22), ('gender', 'Male')])
Iterating Over a Dictionary You can use a for loop to iterate over the keys in a dictionary:
1# Iterating over a dictionary 2for key in my_dict: 3 print(key, my_dict[key])
Output:
1name William 2age 22 3gender Male