您的位置:首页 > 编程语言 > Python开发

Python学习笔记-Dictionary 【python 3】//为继续学习爬虫准备-00

2016-09-08 18:47 525 查看
dictionary是N组无序的键值对的集合,每个dictionary由一个花括号括起来,每组数据由“;”隔开,key:value 作为一个元素。
通过一个dictionary的key可以查找到value值。
如下面这个exDict的dictionary,key是人名,value是对应的人的年级:
exDict={"andy":20,"bob":2,"chris":30,"dave":21,"edith":26}


打印出上面的exDict,可以看到dictionary打印出来的键值对是无序的 
>>> print (exDict)
{'chris': 30, 'dave': 21, 'bob': 2, 'edith': 26, 'andy': 20}


使用keys()输出所有的key
>>> exDict.keys()
dict_keys(['chris', 'dave', 'bob', 'edith', 'andy'])

#或者
>>> list(exDict.keys())
['chris', 'dave', 'bob', 'edith', 'andy']


使用items()输出所有的键值对 
>>> exDict.items()
dict_items([('chris', 30), ('dave', 21), ('bob', 2), ('edith', 26), ('andy', 20)])

#或者
>>> list(exDict.items())
[('chris', 30), ('dave', 21), ('bob', 2), ('edith', 26), ('andy', 20)]


使用values()输出所有的value
>>> exDict.values()
dict_values([30, 21, 2, 26, 20])


如果要查找一个key的值,直接dictionary['key']即可,如:
>>> exDict['andy']
20


添加一组key:value,直接dictionary['key']=value 
exDict['frank'] = 20


修改一个元素
exDict['bob'] = 12


删除一个元素
del exDict['bob']

#或者
exDict.pop('chris')


删除多个元素
for _ in['andy','frank']: del(exDict[_])


最后结果:
>>> print(exDict)
{'dave': 21, 'edith': 26}


清空一个dictionary,直接使用.clear()即可:
>>> exDict.clear()
>>> exDict
{} #得到一个空的花括号


复制一个dictionary,使用copy(): 
>>> dict1 = {'chinese':0,'english':1,'french':2,'spanish':3}
>>> dict2 = dict1.copy()
>>> dict2
{'french': 2, 'chinese': 0, 'spanish': 3, 'english': 1}


检查一个key是否在dictionary里 【使用has_key('key'),返回布尔值: 这个方法仅适用于python 2 】
>>> dict1.has_key('english')
True
>>> dict2.has_key('japanese')
False


python3 用1. key in dictionary: 
>>> 'french' in dict1
True
>>> 'japanese' in dict1
False


python3 还可以用2. dictionary.__contains__('key')
>>> dict2.__contains__('chinese')
True
>>> dict2.__contains__('hebrew')
False
>>>


根据key给一个dictionary排序 【利用sorted()定义函数】
>>> def sortBK():
...     sortBKs = sorted(dict2.items(),key=lambda t:t[0])
...     print sortBKs
...
>>> sortBK()
[('chinese', 0), ('english', 1), ('french', 2), ('spanish', 3)]


可以看到我们得到一个按照首字母排序的list (我们不会得到一个dictionary是因为dictionary是无序的)

根据value给一个dictionary排序类似(虽然似乎看不出dictionary的排序):
>>> def sortBV():
...     sortBVs = sorted(dict2.items(),key=lambda t:t[1])
...     print(sortBVs)
...
>>> sortBV()
[('chinese', 0), ('english', 1), ('french', 2), ('spanish', 3)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python