DICTIONARIES
Dictionaries in Python are unordered collections of items. Unlike sequences such as lists or tuples, which are indexed by a range of numbers, dictionaries are indexed by keys. Keys can be any immutable type, such as strings and numbers, while values can be any data type, including lists, tuples, other dictionaries, or even functions. Dictionaries are defined using curly braces {}
and key-value pairs separated by colons :
.
Creating a Dictionary:
You can create a dictionary by providing key-value pairs within curly braces {}
.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
Accessing Elements:
You can access the value associated with a specific key by using square brackets []
with the key.
print(my_dict['name']) # Output: John
Modifying a Dictionary:
You can modify the value associated with a key by assigning a new value to it.
my_dict['age'] = 35
print(my_dict) # Output: {'name': 'John', 'age': 35, 'city': 'New York'}
Adding Elements:
You can add new key-value pairs to a dictionary by assigning a value to a new key.
my_dict['gender'] = 'Male'
print(my_dict) # Output: {'name': 'John', 'age': 35, 'city': 'New York', 'gender': 'Male'}
Removing Elements:
You can remove a key-value pair from a dictionary using the del
keyword or the pop()
method.
del my_dict['city']
print(my_dict) # Output: {'name': 'John', 'age': 35, 'gender': 'Male'}
removed_age = my_dict.pop('age')
print(removed_age) # Output: 35
Dictionary Methods:
Dictionaries come with several built-in methods for performing various operations.
keys()
: Returns a view object containing the keys of the dictionary.values()
: Returns a view object containing the values of the dictionary.items()
: Returns a view object containing the key-value pairs of the dictionary as tuples.
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'gender'])
print(my_dict.values()) # Output: dict_values(['John', 35, 'Male'])
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 35), ('gender', 'Male')])
Dictionaries are versatile data structures used for mapping keys to values and are commonly used in various applications due to their flexibility and efficiency.
Sure, here are some commonly used dictionary methods in Python:
1. clear()
:
Clears all the elements from the dictionary.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict.clear()
print(my_dict) # Output: {}
2. copy()
:
Returns a shallow copy of the dictionary.
my_dict = {'name': 'John', 'age': 30}
new_dict = my_dict.copy()
print(new_dict) # Output: {'name': 'John', 'age': 30}
3. get(key, default=None)
:
Returns the value associated with the specified key. If the key is not found, it returns the default value (which defaults to None
if not provided).
my_dict = {'name': 'John', 'age': 30}
print(my_dict.get('name')) # Output: John
print(my_dict.get('city', 'Unknown')) # Output: Unknown
4. pop(key, default=None)
:
Removes the item with the specified key and returns its value. If the key is not found, it returns the default value (or raises a KeyError
if not provided).
my_dict = {'name': 'John', 'age': 30}
removed_name = my_dict.pop('name')
print(removed_name) # Output: John
print(my_dict) # Output: {'age': 30}
5. popitem()
:
Removes and returns an arbitrary key-value pair as a tuple. Raises a KeyError
if the dictionary is empty.
my_dict = {'name': 'John', 'age': 30}
removed_item = my_dict.popitem()
print(removed_item) # Output: ('age', 30)
print(my_dict) # Output: {'name': 'John'}
6. update(iterable)
:
Updates the dictionary with elements from another dictionary or from an iterable of key-value pairs.
my_dict = {'name': 'John', 'age': 30}
my_dict.update({'city': 'New York'})
print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
These are just a few of the many methods available for dictionaries in Python. Each method provides a convenient way to manipulate dictionaries according to your requirements.