码迷,mamicode.com
首页 > 其他好文 > 详细

pyhon 字典

时间:2017-11-03 11:12:17      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:python

字典

>>> a = {}                                     #创建空字典

>>> b = {‘name‘:‘tt‘,‘age‘:‘18‘}                      #创建字典

>>> b[‘name‘]                                   #访问字典里的值

‘tt‘

>>> b[‘sex‘]= ‘man‘                               #添加字典

>>> b

{‘name‘: ‘tt‘, ‘age‘: ‘18‘, ‘sex‘: ‘man‘}

>>> b[‘age‘]= 28                                 #修改字典

>>> b

{‘name‘: ‘tt‘, ‘age‘: 28, ‘sex‘: ‘man‘}

>>> c = b.copy()                                 #字典复制           

>>> c

{‘name‘: ‘tt‘, ‘age‘: 28, ‘sex‘: ‘man‘}

>>> del b[‘name‘]                                #删除字典键

>>> b

{‘age‘: 28, ‘sex‘: ‘man‘}  

>>> del b                                      #删除字典

>>> b

Traceback (most recent call last):

  File "<pyshell#12>", line 1, in <module>

    b

NameError: name ‘b‘ is not defined


>>> c1 = c.setdefault(‘name‘,‘df‘)        #键存在,不改动,返回字典中相应的键对应的值

>>> c1

‘tt‘

>>> c

{‘name‘: ‘tt‘, ‘age‘: 28, ‘sex‘: ‘man‘}         

>>> c2 = c.setdefault(‘height‘,‘180‘)      #键不存在,在字典中中增加新的键值对,并返回相应的值

>>> c2

‘180‘

>>> c

{‘name‘: ‘tt‘, ‘age‘: 28, ‘sex‘: ‘man‘, ‘height‘: ‘180‘}

>>> c.items()

dict_items([(‘name‘, ‘tt‘), (‘age‘, 28), (‘sex‘, ‘man‘), (‘height‘, ‘180‘)])

>>> c.keys()

dict_keys([‘name‘, ‘age‘, ‘sex‘, ‘height‘])

>>> c.values()

dict_values([‘tt‘, 28, ‘man‘, ‘180‘])

>>> d ={‘hobby‘:‘girl‘}

>>> c.update(d)

>>> c

{‘name‘: ‘tt‘, ‘age‘: 28, ‘sex‘: ‘man‘, ‘height‘: ‘180‘, ‘hobby‘: ‘girl‘}

>>> c3 = c.pop(‘hobby‘)                 #删除字典中指定键值对,并返回该键值对的值

>>> c3

‘girl‘

>>> c

{‘name‘: ‘tt‘, ‘age‘: 28, ‘sex‘: ‘man‘, ‘height‘: ‘180‘}

>>> c4 = c.popitem()                   #随机删除某组键值对,并以元组方式返回值

>>> c4

(‘height‘, ‘180‘)

>>> c

{‘name‘: ‘tt‘, ‘age‘: 28, ‘sex‘: ‘man‘}

>>> c.clear()                        #清空字典

>>> c

{}


fremkeys()方法用于创建并返回一个新的字典,它有两个参数:字典的键;第二个参数可选,传入键对应值,不提供默认none

>>> e = {}

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

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

>>> e.fromkeys((1,2,3),‘shu‘)

{1: ‘shu‘, 2: ‘shu‘, 3: ‘shu‘}

>>> e

{}

>>> e.fromkeys((1,2,3),(‘shu‘,‘s‘))

{1: (‘shu‘, ‘s‘), 2: (‘shu‘, ‘s‘), 3: (‘shu‘, ‘s‘)}

>>> e.fromkeys((1,3),‘sa‘)

{1: ‘sa‘, 3: ‘sa‘}

>>> e

{}

>>> e = e.fromkeys(range(6),‘hao‘)

>>> e

{0: ‘hao‘, 1: ‘hao‘, 2: ‘hao‘, 3: ‘hao‘, 4: ‘hao‘, 5: ‘hao‘}

>>> f = str(e)                        #字典转换为字符串

>>> f

"{0: ‘hao‘, 1: ‘hao‘, 2: ‘hao‘, 3: ‘hao‘, 4: ‘hao‘, 5: ‘hao‘}"

>>> type(f)

<class ‘str‘>

>>> g = eval(f)                        #字符串转换为字典

>>> g

{0: ‘hao‘, 1: ‘hao‘, 2: ‘hao‘, 3: ‘hao‘, 4: ‘hao‘, 5: ‘hao‘}

>>> type(g)

<class ‘dict‘>


本文出自 “每天进步一点点” 博客,请务必保留此出处http://zuoshou.blog.51cto.com/2579903/1978493

pyhon 字典

标签:python

原文地址:http://zuoshou.blog.51cto.com/2579903/1978493

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!