Create by westfallon on 7/2
字典的本質: 由鍵值對構成的集合
- item = (key, value)
字典的賦值
- 同列表一樣
a_dict = {'one': 1, 'two': 2, 'three': 3} another_list = a_dict another_list['one'] = 4 print(a_dict) # 結果: {'one': 4, 'two': 2, 'three': 3}
字典的復制
- 與列表不一樣, 使用copy()函數(shù)進行復制
a_dict = {'one': 1, 'two': 2, 'three': 3} a_new_dict = a_dict.copy() a_new_dict['one'] = 4 print(a_dict) # 結果: {'one': 1, 'two': 2, 'three': 3}
keys(), values(), items()函數(shù)的使用
- keys()函數(shù)的功能是獲取字典中的所有鍵
a_dict = {'one': 1, 'two': 2, 'three': 3} a_dict_keys = a_dict.keys() print(a_dict_keys) # 結果: dict_keys(['one', 'two', 'three'])
- values()函數(shù)的功能是獲取字典中的所有值
a_dict = {'one': 1, 'two': 2, 'three': 3} a_dict_values = a_dict.values() print(a_dict_values) # 結果: dict_values([1, 2, 3])
- items()函數(shù)的功能是獲取字典中的所有鍵值對
a_dict = {'one': 1, 'two': 2, 'three': 3} a_dict_items = a_dict.items() print(a_dict_items) # 結果: dict_items([('one', 1), ('two', 2), ('three', 3)])
in 與 not in 的用法
- in 用于判斷某元素是不是字典中的key, 常與if和while語句連用
a_dict = {'one': 1, 'two': 2, 'three': 3} if 'one' in a_dict: print("one is a key in dict ") # 結果: one is a key in dict
get()函數(shù)的使用
- get()函數(shù)的功能是獲取key對應的value, 與dict[]功能相同
a_dict = {'one': 1, 'two': 2, 'three': 3} print(a_dict['one']) print(a_dict.get('one')) # 結果: # 1 # 1
字典生成式
- 與列表生成式一樣, 格式為:
new_dict = {key: value for key, value in dict if }