字典是一种可变容器类型,可以存储任意类型对象
key : value,其中value可以是任何数据类型,key必须是不可变的如字符串、数字、元组,不可以用列表
key是唯一的,如果出现两次,后一个值会被记住
字典的创建
创建空字典
dictionary = {}
直接赋值创建字典
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175}
通过关键字dict和关键字参数创建字典
dictionary = dict(name='Nick', age=20, height=175)
dictionary = dict()
for i in range(1, 5):
dictionary[i] = i * i
print(dictionary) # 输出结果:{1: 1, 2: 4, 3: 9, 4: 16}
通过关键字dict和二元组列表创建
my_list = [('name', 'Nick'), ('age', 20), ('height', 175)]
dictionary = dict(my_list)
通过关键字dict和zip创建
dictionary = dict(zip('abc', [1, 2, 3]))
print(dictionary) # 输出{'a': 1, 'b': 2, 'c': 3}
通过字典推导式创建
dictionary = {i: i ** 2 for i in range(1, 5)}
print(dictionary) # 输出{1: 1, 2: 4, 3: 9, 4: 16}
通过dict.fromkeys()来创建
dictionary = dict.fromkeys(range(5), 'x')
print(dictionary) # 输出{0: 'x', 1: 'x', 2: 'x', 3: 'x'}
这种方法用来初始化字典设置value的默认值
字典的访问
通过键值对访问
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175}
print(dictionary['age'])
通过dict.get(key, default=None)访问:default为可选项,指定key不存在时返回一个默认值,如果不设置默认返回None
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}
print(dictionary.get(3, '字典中不存在键为3的元素'))
遍历字典的items
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}
print('遍历输出item:')
for item in dictionary.items():
print(item)
print('\n遍历输出键值对:')
for key, value in dictionary.items():
print(key, ' : ', value)
遍历字典的keys或values
dictionary = {'name' : 'Nick', 'age' : 20, 'height' : 175, 2 : 'test'}
print('遍历keys:')
for key in dictionary.keys():
print(key)
print('\n通过key来访问:')
for key in dictionary.keys():
print(dictionary[key])
print('\n遍历value:')
for value in dictionary.values():
print(value)
遍历嵌套字典
for key, value in dict_2.items():
if type(value) is dict: # 通过if语句判断value是不是字典
for sub_key, sub_value in value.items():
print(sub_key, "→", sub_value)
使用[]
dictionary = {}
dictionary['name'] = 'Nick'
dictionary['age'] = 20
dictionary['height'] = 175
print(dictionary)
使用update()方法
dictionary = {'name': 'Nick', 'age': 20, 'height': 175}
dictionary.update({'age' : 22}) # 已存在,则覆盖key所对应的value
dictionary.update({'2' : 'tetst'}) # 不存在,则添加新元素
print(dictionary)
字典作为参数传递时:函数内对字典修改,原来的字典也会改变
dictionary = {'name': 'Nick', 'age': 20, 'height': 175}
dictionary.update({'age': 22}) # 已存在,则覆盖key所对应的value
dictionary.update({'2': 'test'}) # 不存在,则添加新元素
print(dictionary)
def dict_fix(arg):
arg['age'] = 24
dict_fix(dictionary)
print(dictionary) # age : 24
字典作为可变参数时:函数内对字典修改,不会影响到原来的字典
dictionary = {'name': 'Nick', 'age': 20, 'height': 175}
dictionary.update({'age': 22}) # 已存在,则覆盖key所对应的value
dictionary.update({'2': 'test'}) # 不存在,则添加新元素
print(dictionary, '\n')
def dict_fix(**arg):
for key, value in arg.items():
print(key, '->', value) # age : 22
arg['age'] = 24
dict_fix(**dictionary)
print('\n', dictionary) # age : 22
关于字典作为**可变参数时的key类型说明
dictionary = {}
dictionary.update({2: 'test'})
print(dictionary, '\n')
def dict_fix(**arg):
for key, value in arg.items():
print(key, '->', value)
arg['age'] = 24
dict_fix(**dictionary)
dictionary = {}
dictionary.update({2: 'test'})
print(dictionary, '\n')
def dict_fix(arg):
for key, value in arg.items():
print(key, '->', value)
arg['2'] = 'new'
dict_fix(dictionary)
补充一个例子
def function(*a,**b):
print(a)
print(b)
a=3
b=4
function(a, b, m=1, n=2) # (3, 4) {'n': 2, 'm': 1}
使用python内置排序函数
sorted(iterable, key=None, reverse=False)
iterable:可迭代对象;key:用来比较的元素,取自迭代对象中;reverse:默认False升序, True降序
data = sorted(object.items(), key=lambda x: x[0]) # 使用x[0]的数据进行排序
内置函数
cmp(dict1, dict2) # 比较两个字典元素的大小,该函数在python3中已弃用;
# 比较原理:先比较类型如数字比字符串小、字符串类型比列表小;类型一致比较取值,数字按大小,字符按顺序等
len(dict) # 计算字典元素个数,即key的总个数
type(variable) # 返回变量类型,判断是否为dict等
内置方法
dict.clear() # 删除字典内所有元素
dict.copy() # 返回一个字典的浅复制
dict.fromkeys(seq, val) # 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键的初始值
dict.get(key, default=None) # 如前介绍,通过key获取value
dict.items() # 以列表返回可遍历的(键, 值)元组数组
dict.keys() # 以列表返回一个字典所有的键
dict.values() # 以列表返回字典中的所有值
dict.update(dict2) # 把字典dict2中的键值对更新到dict中,有:更新;没有:添加
dict.setdefault(key, default=None) # 与get类似。如果存在key则返回value,不存在则添加key并设置default value
dict.pop(key, default) # 删除key所对应的值,返回对应的value; key不给出则返回default
dict.popitem() # 返回并删除字典中最后一对(key, value)
【参考文章】
字典的创建方式
字典的访问1
字典的访问2
字典中添加元素
字典作为函数参数1
字典通过关键字参数传参
字典作为可变参数时的key取值问题
*参数和** 形参的区别
字典cmp函数1
字典cmp函数2
python字典常用方法
python字典内置函数总结
created by shuaixio, 2023.10.05