Python基础- dict和set

Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度

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'])
原文地址:https://www.cnblogs.com/wangpfcnblogs/p/6680515.html