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()函数进行复制
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()函数的使用
- keys()函数的功能是获取字典中的所有键
a_dict = {'one': 1, 'two': 2, 'three': 3} a_dict_keys = a_dict.keys() print(a_dict_keys) # 结果: dict_keys(['one', 'two', 'three']) - values()函数的功能是获取字典中的所有值
a_dict = {'one': 1, 'two': 2, 'three': 3} a_dict_values = a_dict.values() print(a_dict_values) # 结果: dict_values([1, 2, 3]) - items()函数的功能是获取字典中的所有键值对
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()函数的使用
- get()函数的功能是获取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 }