📜  dict 理解 - Python (1)

📅  最后修改于: 2023-12-03 15:00:24.711000             🧑  作者: Mango

Python Dictionary

Python dictionary is an unordered collection of key-value pairs. It is one of the most frequently used data structures in Python programming.

Creating a Dictionary

A dictionary can be created by placing a comma-separated list of key-value pairs inside braces {}. Each key-value pair is separated by a colon :. Here's an example:

# Creating a dictionary
person = {"name": "John", "age": 20, "gender": "Male"}
Accessing Values

You can access the values of a dictionary by referring to its key name inside square brackets []. Here's an example:

# Accessing values of a dictionary
print(person["name"])   # Output: John
print(person["age"])    # Output: 20
Updating Values

You can update the value of a dictionary by referring to its key name and assigning its new value. Here's an example:

# Updating the value of a dictionary
person["age"] = 25
print(person["age"])    # Output: 25
Looping Through a Dictionary

You can loop through a dictionary by using a for loop and referring to its keys. Here's an example:

# Looping through a dictionary
for key in person:
    print(key, person[key])
Dictionary Methods

Python dictionary provides several methods to perform various tasks. Some commonly used methods are:

  • keys(): Returns a list of all the keys in the dictionary.
  • values(): Returns a list of all the values in the dictionary.
  • items(): Returns a list of all the key-value pairs in the dictionary.
  • pop(): Removes the element with the specified key and returns its value.
  • clear(): Removes all the elements from the dictionary.
Conclusion

Python dictionary is a powerful and versatile data structure that can help you to store, access, and manipulate key-value pairs. It provides several methods to perform various tasks, and it is an essential tool for any Python programmer.