📅  最后修改于: 2023-12-03 14:45:57.298000             🧑  作者: Mango
Python Dictionary is a built-in data structure to store data in key-value pairs. It's similar to associative arrays or hash tables in other programming languages. In a dictionary, keys are unique and immutable; the values, however, can be of any data type and can be modified.
A dictionary is created using curly braces {} and using a colon (:) to separate keys and values. The syntax is as follows:
# Creating a dictionary
dictionary_name = {key1: value1, key2: value2, key3: value3}
To access the values of a dictionary, we use square brackets [] and the key.
# Accessing Values
dictionary_name[key]
We can also use the get() method to access the values. The method returns None if the key doesn't exist.
# Using the get() method
dictionary_name.get(key)
To add or modify a value in the dictionary, we use the assignment operator =.
# Adding/Modifying values
dictionary_name[key] = value
To remove a key-value pair from a dictionary, we can use the del statement.
# Removing a key-value pair
del dictionary_name[key]
If we want to create a dictionary with the keys already defined, we can use the dict() constructor method.
# Creating a dictionary using keys defined as a list
keys_list = ['key1', 'key2', 'key3']
dictionary_name = dict.fromkeys(keys_list)
In conclusion, Python Dictionary is an essential data structure in Python. It provides a quick and efficient way to store and access data using keys and values.
Note: The order of the key-value pairs in the dictionary is not guaranteed.
Happy coding!