Python Dictionary Operations
In Python, a dictionary (short for dict) is a mutable container model used to store key-value pairs. Each key in the dictionary maps to a value. Unlike lists and tuples, elements within a dictionary are unordered.
Dictionaries are created using curly braces {}, with keys separated from values by colons : and key-value pairs separated by commas ,. For example, here is an example of a dictionary containing two key-value pairs:
my_dict = {"apple": 1.99, "banana": 0.99}
To access a value in the dictionary, you can use its corresponding key as an index:
my_dict["apple"]
To add a new key-value pair to the dictionary, assign it directly to a new key:
my_dict["pear"] = 2.49
To modify a value in the dictionary, you can assign a new value directly through its key:
my_dict["apple"] = 2.49
To delete a key-value pair from the dictionary, use the del keyword:
del my_dict["banana"]
Dictionaries support many common operations, such as retrieving all keys, retrieving all values, and getting the count of key-value pairs, etc. For example, to retrieve a list of all keys, you can use the following syntax:
my_dict.keys()
To retrieve a list of all values, you can use the following syntax:
my_dict.values()
To get the count of key-value pairs, you can use the following syntax:
len(my_dict)
Dictionaries are widely used in many Python applications for various purposes, such as storing configuration information or representing database records.