Python 全栈开发:dict(字典)常用方法操作、dict嵌套

摘要:
无序(3.5及更早版本)#dict={#'name':[{'num':'male'}#increment dict['key']:则该值覆盖#print(“dict1['high']=185和ict1['age']=16”,#dict1['high']=1.85和ict1['age']=16{'high':无数据类型#print(dict1)。pop(“age”),

  数据类型的划分:可变数据类型和不可变数据类型。

  不可变数据类型(可哈希):元祖、bool、int、str

  可变数据类型(不可哈希):list、dict,set(集合)

  dict(字典):

   dict(字典):映射数据类型

   dict =  {"key":value}

   dict key 必须不可变数据类型,可哈希。

  value  任意数据类型

   dict 优点:二分法查找去查询

     存储大量的关系型数据

    特点:无序的(3.5及其之前的版本)

# dict = {
# 'name':['韩非','黄有华','林颖','谢龙','李霞霞','纪伟鹏'],
# '配送':[{'num':12,'avera_age':20}],
# True:1,
# (1,2,3):'wuyiyi',
# 2:'二哥',
# }
# print(dict)
#例子
# dict1 = {'age':18,'name':'jone','sex':'male'}

#增 dict['key']:value 或 setdefault(key,value)
# dict1['hight']=185 #没有键值对,添加
# dict1['age'] = 16 #如果有键值对,则值覆盖
# print("dict1['hight']=185 and dict1['age']=16",dict1)
# 输出结果:
# dict1['hight']=185 and dict1['age']=16 {'hight': 185, 'sex': 'male', 'age': 16, 'name': 'jone'}
#setdefault() 已经存在键值对,不做任何改变,没有在添加
# dict1.setdefault('weight',150)
# dict1.setdefault('name','alex')
# print(dict1)
# 输出结果:
# dict1['hight']=185 and dict1['age']=16 {'hight': 185, 'sex': 'male', 'age': 16, 'name': 'jone'}

#删 pop(key,'设置返回值')、popitem(key)随机删除,有返回值、del dict[key] 不存在会报错、clear()清空字典
#ps:None是一种数据类型
# print(dict1.pop('age'),dict1)
# print(dict1.pop('yijiajun',None),dict1)
# 输出结果:
# 18 {'name': 'jone', 'sex': 'male'}
# None {'name': 'jone', 'sex': 'male'}
# print(dict1.popitem(),dict1)
# 输出结果:
# ('name', 'jone') {'sex': 'male', 'age': 18}
# del dict1['age']
# print(dict1)
# 输出结果:
# {'name': 'jone', 'sex': 'male'}
# del dict1
# print(dict1)
# 输出结果:
# print(dict1)
# NameError: name 'dict1' is not defined

#改
# dict1['age'] = 20
# print(dict1)
# 输出结果:
# {'name': 'jone', 'sex': 'male', 'age': 20}
#update() 已经存在的键值对,会更新value,不存在的键值对,则添加
# dict2 = {'name':'yijiajun','heigh':175,'weight':75}
# dict1.update(dict2)
# print(dict1,dict2)

#查
# print(dict1.keys(),type(dict1.keys()))
# print(dict1.values(),type(dict1.values()))
# print(dict1.items(),type(dict1.items()))
# print(dict1.get('name'),type(dict1.get('name')))
# print(dict1.get('yijia'),'不存在key')
# 输出结果:
# dict_values([18, 'male', 'jone']) <class 'dict_values'>
# dict_items([('age', 18), ('sex', 'male'), ('name', 'jone')]) <class 'dict_items'>
# jone <class 'str'>
# None 不存在key

#for .....in.....遍历任何项目的序列
#遍历key
#方法一
# for i in dict1.keys():
# print(i)
#方法二
# for i in dict1:
# print(i)
#遍历value
# for i in dict1.values():
# print(i)
#以元祖的形式同时遍历key和value
# for i in dict1.items():
# print(i,type(i))
# 输出结果:
# ('sex', 'male') < class 'tuple'>
# ('name', 'jone') <class 'tuple'>
# ('age', 18) < class 'tuple'>
#以字符串的形式同时遍历key和value
# for k,v in dict1.items():
# print(k,v,type(k),type(v))
# 输出结果:
# dict_values([18, 'male', 'jone']) <class 'dict_values'>
# dict_items([('age', 18), ('sex', 'male'), ('name', 'jone')]) <class 'dict_items'>
# jone <class 'str'>
# None 不存在key

#字典嵌套
# dic = {
# 'name':['yijiajun','yijiaping','yijiaxing'],
# 'home.yee':{
# 'born' :1995,
# 'count':85,
# 'old':'grandfather'
# },
# True:1,
# (1,2,3):'yimeiling',
# 'age':21
#
# }
# dic['age'] = 56
# dic['name'][0] = dic['name'][0].upper()
# dic['name'].append('wangxizhi')
# dic['home.yee']['color'] = 'red'
# dic['home.yee'].setdefault('like','fish')
# dic['home.yee'].pop('born','已经删除')
# print(dic['home.yee'].pop('born','已经删除'))

#课间题 统计数字出现的次数(连续的数字为1个)
info = input('请输入您要检测的数字:').strip()
for i in info:
if i.isalpha():
info = info.replace(i,' ')
l = info.split( )
print(l)
print(len(l))


免责声明:文章转载自《Python 全栈开发:dict(字典)常用方法操作、dict嵌套》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇无限加载 vue用infinite-loading插件和阿波罗请求SpringBoot集成SpringSecurity+CAS下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

window下安装itchat库

itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。 pip 是 Python 著名的包管理工具,在 Python 开发中必不可少。 1、安装   检查你有没有安装了pip:运行,输入cmd,回车,输入pip,回车。如果提示“'pip' 不是内部或外部命令”,原因是电脑本地没有安装pip命令。   这有两种办法安装pip:   A...

vue_相同组件,不同url跳转不重新渲染的解决方法

最近写的这个项目,有很多下拉菜单,每个菜单会有相应的两种类型。现在产品的需求是,跳转到不同的类型 需要页面重新渲染数据 那么问题来了。 我试了好几种方法,用watch监听路由去判断,但是发现输在input里面的值是不会被替换掉的 所以想到了用key 去如果不使用key,Vue会使用一种最大限度减少动态元素并且尽可能的尝试修复/再利用相同类型元素的算法。使用...

MySQL复合主键下ON DUPLICATE KEY UPDATE语句失效问题

问题的起因,假设有一张表,里面保存了交易订单,每张订单有唯一的ID,有最后更新时间,还有数据,详情如下: 1 2 3 4 5 6 7 +-------+----------+------+-----+---------------------+-------+ |Field|Type|Null|Key|Default|Extra| +--...

UOS安装zerotier-one

一、在线安装方式 下载安装 curl -s https://install.zerotier.com/ | sudo bash 添加开机自启 sudo systemctl enable zerotier-one.service 启动zerotier-one.service sudo systemctl start zerotier-one.servic...

Map/HashMap 获取Key值的方法

1、通过 KeySet()方法 Map<String,Student> newmap = new HashMap<String,Student>(); //newmap HaspMap类型的集合 有唯一的Key,一个Key对应相应的学生 Student stu = new Student("11","Mary","...

vue中的锚链接跳转问题

一、在vue中的锚链接和普通的html不同 关于vue中的锚链接可以参考vue 中的  scrollBehavior 滚动行为。 在router.js中  const router = new VueRouter({     routes,       mode: 'history',       scrollBehavior(to, fro...