a6657266的个人博客分享 http://blog.sciencenet.cn/u/a6657266

博文

python中dictionary的用法小结

已有 8203 次阅读 2013-7-9 16:42 |系统分类:科研笔记| Python, Dictionary

参考:http://docs.python.org/2/library/stdtypes.html#typesmapping 

>>> a=dict(one=1,two=2,three=3)

>>> b={'one':1,'two':2,'three':3}

>>> c=dict(zip(['one','two','three'],[1,2,3]))

>>> d=dict([('two',2),('one',1),('three',3)])

>>> e=dict({'three':3,'one':1,'two':2})

>>> a==b==c==d==e

True

len(d):d的item个数

d[key]=value 给关键字是key的item赋值

key in d: 如果key关键字在d里,返回true

clear():删除所有的items

iter(d):Return an iterator over the keys of the dictionary.  This is a shortcutfor iterkeys().

fromkeys(seq[, value]):Create a new dictionary with keys from seq and values set to value.

fromkeys() is a class method that returns a new dictionary. value defaults to None.

get(key[, default]):如果key存在的话,返回值,如果不存在,就返回空值,这个函数永远不报错keyError.

has_key(key):检测key是否存在.  has_key() isdeprecated in favor of keyind.

pop(key[, default]):如果key在dictionary里面,返回值,否则返回空值,如果关键字不存在而且没有赋空值,报错,KeyError.

其他的看网址~~吼吼~~·

例子:

>>> dishes={'eggs':2,'sausage':1,'bacon':1,'spam':500}

>>> keys=dishes.viewkeys()

>>> values=dishes.viewvalues()

>>> # iteration

>>> n=0

>>> for val in values:

        ... n+=val

>>> print(n)

504
 

>>> # keys and values are iterated over in the same order

>>> list(keys)

['eggs', 'bacon', 'sausage', 'spam']

>>> list(values)

[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes

>>> del dishes['eggs']

>>> del dishes['sausage']

>>> list(keys)

['spam', 'bacon']

>>> # set operations

>>> keys&{'eggs','bacon','salad'}

{'bacon'}


key|{'eggs','bacon','salad'} 返回并集

key-{'eggs','bacon','salad'}返回key有,{'eggs','bacon','salad'}没有的

key^{'eggs','bacon','salad'}返回不是key与{'eggs','bacon','salad'}都有的












https://blog.sciencenet.cn/blog-571755-706682.html

上一篇:关于python中,docstring的写法
下一篇:python中的list用法简单小结
收藏 IP: 210.72.26.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-3-29 21:54

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部