字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key:value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中
dict1={'apple':23,'banana':34,'cherry':6}
dict2={'java':[1,2],'python':[3,4],'c++':[5,6]}
dict3={'java':{'year':'1996','url':'www/baidu.com','score':[20,30,40]},'python':{'year':'1994','url' :'www/baidu.com','score':[50,60,70]}}
访问字典里的值
获取字典里的值方式有两种,一个是通过字典的key值下标获取对应value,还可以通过get方法获取对应value

区别:使用key下标的方式,如果用字典里没有的键访问数据,会抛KeyError的异常。而使用get方法,如果键不在字典中返回默认值 None 或者设置的默认值。
修改字典
dict1={'apple':23,'banana':34,'cherry':6}
dict1['apple'] = 8 # 更新
dict1['orange'] = 34 # 添加
删除字典元素
dict3 ={'java':[1,2],'python':[3,4],'c++':[5,6]}
#========删除元素
print('删除前',dict3)
del dict3['java']
print('删除后',dict3)
#=======清空字典所有条目
print('清空字典所有条目',dict3.clear())
#========删除字典
del dict3
嵌套字典遍历与内置函数
items()—函数 Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
#======items函数 嵌套for循环
dict3={'java':{'year':'1996','url' :'www/baidu.com','score':[20,30,40]},'python':{'year':'1994','url' :'www/baidu.com','score':[50,60,70]}}
for key,value in dict3.items():
print('外层key',key)
print('外层value',value)
for key1,value1 in value.items():
print('内层key',key1)
print('内层value',value1)
keys() — Python 字典(Dictionary) keys() 函数以列表返回一个字典所有的键。values() — Python 字典(Dictionary) values() 函数以列表返回字典中的所有值。
#========方法二 使用keys() ,values() 函数获取嵌套字典的所有key,value
dict3={'java':{'year':'1996','url' :'www/baidu.com','score':[20,30,40]},'python':{'year':'1994','url' :'www/baidu.com','score':[50,60,70]}}
print(dict3.keys())
for i in range(len(list(dict3.values()))):
print(list(dict3.values())[i].values())
fromkeys() —Python 字典 fromkeys() 函数用于创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值。
seq = ('Google', 'Runoob', 'Taobao')
# 不指定默认的键值,默认为 None
thisdict = dict.fromkeys(seq)
print ("新字典为 : %s" % str(thisdict))
# 指定默认的键值
thisdict = dict.fromkeys(seq, 10)
print ("新字典为 : %s" % str(thisdict))
popitem()—Python 字典 popitem() 方法返回并删除字典中的最后一对键和值。
dict2={'java':[1,2],'python':[3,4],'c++':[5,6]}
pop_obj=dict2.popitem()
print(pop_obj)
print(site)
本文介绍了Python字典的使用,包括访问值、修改字典、删除元素以及如何遍历嵌套字典和利用内置函数如items(), keys(), values()等进行操作。强调了get方法在避免KeyError方面的优势,并提到了fromkeys()和popitem()等方法。"
127755099,8225484,MATLAB实现BiLSTM分类预测详解,"['深度学习', '神经网络', '机器学习', 'MATLAB编程', '自然语言处理']

1222

被折叠的 条评论
为什么被折叠?



