一、字典的創建
my_dict = {"name": "John Doe", "age": 30, "city": "New York"}
my_dict = dict(name="John Doe", age=30, city="New York")
my_dict = {key: value for key, value in zip(["name", "age", "city"], ["John Doe", 30, "New York"])}
二、字典的修改
my_dict["job"] = "Software Engineer"
my_dict["age"] = 31
del my_dict["city"]
三、字典的查找
value = my_dict["name"]
get()
方法取得值(如果鍵不存在,則傳回預設值):value = my_dict.get("phone", "Not provided")
if "email" in my_dict: # 键存在,执行某些操作
四、字典的遍歷
for key in my_dict: print(key)
for key, value in my_dict.items(): print(key, value)
dict.values()
和 dict.keys()
):for value in my_dict.values(): print(value) for key in my_dict.keys(): print(key)
五、其他技巧
my_dict1 = {"name": "John Doe", "age": 30} my_dict2 = {"city": "New York", "job": "Software Engineer"} my_dict3 = {**my_dict1, **my_dict2}
my_dict_copy = my_dict.copy()
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
掌握這些技巧,可以幫助您更有效率地使用 python 字典,提高程式碼的品質和效能。
以上是Python 字典技巧錦囊:提升程式碼效率的秘訣的詳細內容。更多資訊請關注PHP中文網其他相關文章!