python中字典操作大全.md
字典是Python是字典中唯一的键-值类型,是Python中非常重要的数据结构,因其用哈希的方式存储数据,速度非常快。下面列出字典的常用的用途.
创建字典的4种方式:
#coding=utf-8 # 如果先能拼出整个字典,则此方法比较方便 Dict1 = {‘name‘:‘聚焦学院‘,‘age‘:6} print(Dict1) # {‘name‘: ‘聚焦学院‘, ‘age‘: 6} # 如果需要动态地建立字典的一个字段,则此方法比较方便 Dict2 = {} Dict2[‘name‘] = ‘聚焦学院‘ Dict2[‘age‘] = 6 print(Dict2) # {‘name‘: ‘聚焦学院‘, ‘age‘: 6} # 代码比较少,但键必须为字符串型。常用于函数赋值 Dict3 = dict(name=‘聚焦学院‘,age=6) print(Dict3) # {‘name‘: ‘聚焦学院‘, ‘age‘: 6} Dict4 = dict(zip((‘name‘,‘age‘),(‘聚焦学院‘,6))) print(Dict4) # {‘name‘: ‘聚焦学院‘, ‘age‘: 6}
字典最常用的方法:
Dict1 = {‘name‘:‘聚焦学院‘,‘age‘:6} print(Dict1) print(Dict1.items()) print(Dict1.keys()) print(Dict1.values()) print(Dict1.pop("name")) print(Dict1) # {‘name‘: ‘聚焦学院‘, ‘age‘: 6} # dict_items([(‘name‘, ‘聚焦学院‘), (‘age‘, 6)]) # dict_keys([‘name‘, ‘age‘]) # dict_values([‘聚焦学院‘, 6]) # 聚焦学院
Dict2 = {} Dict2[‘name‘] = ‘聚焦学院‘ Dict2[‘age‘] = 6 print(Dict2) # {‘name‘: ‘聚焦学院‘, ‘age‘: 6} for key in Dict2: print(Dict2[key]) for value in Dict2.values(): print(value) for key,value in Dict2.items(): print(key,value) # 聚焦学院 # 6 # 聚焦学院 # 6 # name 聚焦学院 # age 6
多层解析:
Dict5={‘name‘:{‘animal‘:[‘cat‘,‘dog‘],‘age‘:[12,10]},‘category‘:‘聚焦学院测试开发‘} print(Dict5[‘name‘][‘animal‘][1]) #dog
更多交流关注公众号:猿桌派
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16