In Python, a dictionary is a collection of key-value pairs. Each key is unique and is used to access the corresponding value. Dictionaries are also known as associative arrays or hash maps.
Dictionaries are defined using curly braces {} and are separated by commas. Each key is followed by a colon and its corresponding value. For example:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
You can also create a dictionary using the built-in dict() function. For example:
my_dict = dict(key1='value1', key2='value2', key3='value3')
You can access the values in a dictionary using the keys. For example:
print(my_dict['key1']) # Output: 'value1'
You can also add, update, and delete items in a dictionary. For example:
Adding an item
my_dict['key4'] = 'value4'
Updating an item
my_dict['key1'] = 'new_value1'
Deleting an item
del my_dict['key2']
Dictionaries also have a number of built-in methods that can be used to perform common operations. Some of these methods include:
- dict.keys(): returns a list of all the keys in the dictionary
- dict.values(): returns a list of all the values in the dictionary
- dict.items(): returns a list of all the key-value pairs in the dictionary
- dict.get(key): returns the value of the key if it exists in the dictionary, otherwise it returns None
- dict.pop(key): removes the key and its corresponding value from the dictionary
- dict.clear(): removes all items from the dictionary
Dictionaries are commonly used in Python for tasks such as counting the frequency of words in a text, storing configuration settings, and creating lookup tables.
No comments:
Post a Comment