设为首页 加入收藏

TOP

Python基础——字典(dict)
2019-03-19 12:07:52 】 浏览:71
Tags:Python 基础 字典 dict

由键-值对构建的集合。

创建

 

dic1={}
type(dic1)

 

dic2=dict()
type(dic2)

 

初始化

dic2={'hello':123,'world':456,'python':789}
dic2
dic2=dict([('hello',123),('world',456)])
dic2

赋值

 

dic1['first']=123
dic1

 

dic1['python']=456
dic1

 

根据键取值

方法1:

若键不存在,则报错。

 

dic1['python']

 

方法2:

若键不存在,则输出指定内容。

dic5.get('hello')
dic5.get('test','没有')

值可以是任意类型

list1=[1,2,3]
dic3={}
dic3["hello"]=list1
dic3['world']=5
dic3
dic4={}
dic_sub1={"hello1":123,"world1":456,"python1":789}
dic_sub2={"hello2":213,"world2":546,"python2":879}
dic4["test1"]=dic_sub1
dic4["test2"]=dic_sub2
dic4

键值运算

dic5={'hello':123,'world':456,'python':789}
dic5['hello']+=1
dic5

弹出

dic5.pop('hello')

删除

del dic5['world']

更新值

用字典2中的值更新字典1中的值。字典2中与字典1中的键相同,则该键的值更新为字典2的,若字典2中的键字典1中并没有,那就添加该键值对。字典2不改变。

dic6={'hello':123,'world':456}
dic7={'hello':789,'python':888}
dic6.update(dic7)
dic6

判断键在不在字典中

'hello' in dic7

获取字典中所有的键值

dic7.keys()
dic7.values()
dic7.items()

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇用内置的库turtle来画一朵花,pyt.. 下一篇金三银四,今年Python就业前,看..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目