Home > Article > Backend Development > Python Dictionary FAQ: Solving Your Troubleshooting
To add key-value pairs in the dictionary, you can use the following two methods:
# 方法一:使用方括号 my_dict["key"] = "value" # 方法二:使用 update() 方法 my_dict.update({"key": "value"})
To find a key in a dictionary, you can use the following two methods:
# 方法一:使用 in 运算符 if "key" in my_dict: print("Key exists") else: print("Key does not exist") # 方法二:使用 get() 方法 value = my_dict.get("key", None) if value is not None: print("Key exists") else: print("Key does not exist")
To delete key-value pairs in the dictionary, you can use the following two methods:
# 方法一:使用 del 关键字 del my_dict["key"] # 方法二:使用 pop() 方法 value = my_dict.pop("key")
Traverse the dictionary, you can use the following two methods:
# 方法一:使用 for 循环 for key, value in my_dict.items(): print(key, value) # 方法二:使用 keys() 和 values() 方法 for key in my_dict.keys(): print(key) for value in my_dict.values(): print(value)
To sort the dictionary, you can use the following two methods:
# 方法一:使用 sorted() 函数 sorted_dict = sorted(my_dict.items(), key=lambda x: x[0]) # 方法二:使用 OrderedDict 类 from collections import OrderedDict ordered_dict = OrderedDict(sorted(my_dict.items(), key=lambda x: x[0]))
To convert a dictionary into a string, you can use the following two methods:
# 方法一:使用 str() 函数 string_dict = str(my_dict) # 方法二:使用 JSON.dumps() 函数 import json string_dict = json.dumps(my_dict)
To convert a string into a dictionary, you can use the following two methods:
# 方法一:使用 eval() 函数 dict_string = "{"key": "value"}" my_dict = eval(dict_string) # 方法二:使用 json.loads() 函数 import json dict_string = "{"key": "value"}" my_dict = json.loads(dict_string)
The above is the detailed content of Python Dictionary FAQ: Solving Your Troubleshooting. For more information, please follow other related articles on the PHP Chinese website!