标签:
>>> a = {‘a‘:1,‘b‘:2} >>> a[‘a‘] 1 >>> b = {‘a‘:[1,2,3],‘b‘:[4,5,6]} >>> b[‘a‘][2] = 5 #KEY ‘a‘ 的第三个值, 改为5. >>> b {‘a‘: [1, 2, 5], ‘b‘: [4, 5, 6]}
>>> a = {2:‘x‘,‘asd‘:‘43‘,(1,2,3):33} >>> a {2: ‘x‘, (1, 2, 3): 33, ‘asd‘: ‘43‘} >>> b = {[1,‘a‘]:"a"} #列表为可变对象, 不能作为"KEY" Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> b = {[1,‘a‘]:"a"} TypeError: unhashable type: ‘list‘
>>> a = {‘a‘:1,‘b‘:2,‘c‘:3} >>> a {‘a‘: 1, ‘c‘: 3, ‘b‘: 2} >>> a[‘d‘] = 4 #增加‘d‘ KEY >>> a {‘a‘: 1, ‘c‘: 3, ‘b‘: 2, ‘d‘: 4} >>> a.update({‘d‘:44}) #更新‘d‘的值, 增加多个也可以 >>> a {‘a‘: 1, ‘c‘: 3, ‘b‘: 2, ‘d‘: 44} >>> a[‘d‘]=88 #修改值 >>> a {‘a‘: 1, ‘c‘: 3, ‘b‘: 2, ‘d‘: 88} >>> del a[‘d‘] #删除值 >>> a {‘a‘: 1, ‘c‘: 3, ‘b‘: 2} >>> a.pop(‘c‘) #删除值 3 >>> a {‘a‘: 1, ‘b‘: 2} >>> a.clear() #清空内容 >>> a {}
#字典, POP方法, 如果KEY不存在, 可以指定返回值 / LIST不可以 >>> a = {‘a‘:1,‘b‘:2,‘c‘:3} >>> a.pop(‘d‘) Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> a.pop(‘d‘) KeyError: ‘d‘ >>> a.pop(‘d‘,‘KEY d is not exist‘) ‘KEY d is not exist‘
#集合has_key()方法 >>> a = {‘a‘:1,‘b‘:2,‘c‘:3} >>> ‘a‘ in a True >>> a.has_key(‘b‘) True >>> "a" not in a False
标签:
原文地址:http://www.cnblogs.com/YoungGu/p/5187638.html