前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python创建和访问字典

Python创建和访问字典

作者头像
py3study
发布2020-01-14 20:07:06
6560
发布2020-01-14 20:07:06
举报
文章被收录于专栏:python3python3python3

>>> dict1 = {'a':'1','b':'2','c':'3','d':'4'}

>>> print('a的值是:',dict1['a'])

a的值是: 1

>>> dict4 = dict('我' = '快乐', 你 = '伤悲')

SyntaxError: keyword can't be an expression

>>> dict4['你'] = '改变悲伤'

>>> dict4

{'我': '快乐', '你': '改变悲伤'}

>>> dict4['他'] = '多加一个'

>>> dict4

{'我': '快乐', '你': '改变悲伤', '他': '多加一个'}

fromkeys(S[,v])    创建并返回一个新的字典

>>> dict1 = {}

>>> dict1.fromkeys((1,2,3))

{1: None, 2: None, 3: None}

>>> dict1.fromkeys((1,2,3),'num')

{1: 'num', 2: 'num', 3: 'num'}

>>> dict1.fromkeys((1,3),'数字')    #如果想用fromkeys修改键的值,不会成功会创建新的字典

{1: '数字', 3: '数字'}

访问字典的方法

keys()

values()

items()

>>> dict2 = {}

>>> dict2 = dict2.fromkeys(range(2),'列子')

>>> dict2

{0: '列子', 1: '列子'}

>>> for eachkey in dict2.keys():    #values为'列子'    

print(eachkey)

0

1

>>> for eachitem in dict2.items():

print(eachitem)

(0, '列子')

(1, '列子')

get() 查找方法

>>> dict2 = dict2.fromkeys(range(10),'列子')

>>> dict2

{0: '列子', 1: '列子', 2: '列子', 3: '列子', 4: '列子', 5: '列子', 6: '列子', 7: '列子', 8: '列子', 9: '列子'}

>>> dict2.get(5,'无')        #如果有则返回值,如果没有则返回'无'

'列子'

>>> dict2.get(10,'无')

'无'

>>> 5 in dict2     #成员操作符判定

True

>>> 10 in dict2

False

clean()     清空一个字典

>>> dict2.fromkeys(range(1),'快乐')

{0: '快乐'}

>>> dict2.clear()

>>> dict2

{}

copy()

>>> a = {1:'one',2:'two',3:'three',4:'four'}

>>> a

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

>>> b = a.copy()

>>> c = a

>>> b

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

>>> c

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

>>> 

>>> c[5] = 'five'

>>> c

{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

>>> a

{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

>>> b

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

pop()

popitem() 随机弹出

>>> a.pop(2)

'two'

>>> a

{1: 'one', 3: 'three', 4: 'four', 5: 'five'}

>>> a.popitem()

(5, 'five')

>>> a

{1: 'one', 3: 'three', 4: 'four'}

>>> a.setdefault(7,'seven')

'seven'

>>> a

{1: 'one', 3: 'three', 4: 'four', 7: 'seven'}

>>> b = {7:'SEVEN'}

>>> a

{1: 'one', 3: 'three', 4: 'four', 7: 'seven'}

>>> a.update(b)

>>> a

{1: 'one', 3: 'three', 4: 'four', 7: 'SEVEN'}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档