Python基础- dict和set
2017-04-07 23:31
337 查看
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
除了初始化时放入的值,还可以可放入
由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉:
如果在dict中key不存在,则就会报错
为了避免key不存在的错误,有两种方法判断可以避免出现错误,一是通过
二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value:
在set中重复的元素会被自动过滤掉
通过add(key)和remove(key)可以向set中添加的删除元素
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
dictionary = {"name" :"Bob", "age" : 12, "city" :"Hangzhou"} dictionary["city"] "Hangzhou"
除了初始化时放入的值,还可以可放入
>>> dictionary = {"name" :"Bob", "age" : 12, "city" :"Hangzhou"} >>> print dictionary {'city': 'Hangzhou', 'age': 12, 'name': 'Bob'} >>> dictionary["score"]= 90 >>> print dictionary {'city': 'Hangzhou', 'age': 12, 'score': 90, 'name': 'Bob'}
由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉:
>>> dictionary["score"]= 100 >>> dictionary["age"]= 30 >>> print dictionary {'city': 'Hangzhou', 'age': 30, 'score': 100, 'name': 'Bob'}
如果在dict中key不存在,则就会报错
>>> dictionary["age"] 30 >>> dictionary["ages"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'ages'
为了避免key不存在的错误,有两种方法判断可以避免出现错误,一是通过
in判断key是否存在:
>>> "age" in dictionary True >>> "ages" in dictionary False
二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value:
>>> dictionary.get("age") #get()方法得到key是age的value 30 >>> dictionary.get("ages","ages not exist") #key不存在,返回自己制定的值 'ages not exist' >>> dictionary.get("ages") #key不存在,返回None >>>
在set中重复的元素会被自动过滤掉
>>> s = set([1,2,2,3,3,4,5]) >>> s set([1, 2, 3, 4, 5])
通过add(key)和remove(key)可以向set中添加的删除元素
>>> s.add("Test") >>> s set([1, 2, 3, 4, 5, 'Test']) >>> s.remove(4) >>> s set([1, 2, 3, 5, 'Test'])
相关文章推荐
- python基础31[list+tuple+set+dict+str+file的成员方法]
- python基础III(dict、set、函数)
- 【2-5】Python基础——dict和set
- 我的python3基础笔记之 【dict和set】 02
- python学习(6)python基础、使用dict和set
- python基础学习——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- 【Python基础】--丰富的else语句/简洁的with语句/字典dict{}/集合set{}
- python基础之Dict和Set类型
- 第四篇:python基础之dict、set及字符
- python基础三_dict&set
- python基础学习四 : Dict和Set类型
- Python基础-Dict 和 Set 类型
- 【Python】基础学习——列表(list),元祖(tuple),字典(dict),字符串(string),集合(set)
- Python基础数据结构之数据转换(Dict,Set,Tuple,List)
- 【Python】 [基础] 条件判断 与 循环 与dict和set
- Python3学习(一)-基础、数据类型、变量、字符串和编码、list&tuple、if、for、while、dict、set、函数与参数
- Python基础8:列表推导式(list)字典推导式(dict) 集合推导式(set)
- Python基础学习--第五篇(Dict和Set类型)
- python基础之字典dict和集合set
- Python基础数据结构之大循环(for list,set,dict,tuple)