dict

  1.建立新字典(根据语法和dict初始化方法)html

>>> my_dict={'a':1,'b':2,'c':3}
>>> my_dict=dict({'a':1,'b':2,'c':3})
>>> mydcit=dict(a=1,b=2,c=3)
>>> mydict=dict([('a',1),('b',2),('c',3)])
>>> mydict=dict(zip(['a','b','c'],[1,2,3]))

2. 建立字典(根据dict的内置函数)函数

  2.1 从sequence里取得keys,建立dictspa

>>> a=['a','b','c']
>>> mydict=dict.fromkeys(a,1)
>>> mydict
{'a': 1, 'c': 1, 'b': 1}

3.更新字典code

d[key] = value:直接改变key对应的value,若是不存在该key,该字典中建立一个key,value的元素。htm

>>> mydict
{'a': 1, 'c': 1, 'b': 1}
>>> mydict['a']=2
>>> mydict
{'a': 2, 'c': 1, 'b': 1}
>>> mydict['d']=4
>>> mydict
{'a': 2, 'c': 1, 'b': 1, 'd': 4}

 

setdefault(key[, default]):若是存在key,那么就返回该key对应的value,不然该字典中建立一个key,value的元素。并返回default值blog

>>> mydict.setdefault('a',3)
2
>>> mydict
{'a': 2, 'c': 1, 'b': 1, 'd': 4}
>>> mydict.setdefault('e',5)
5
>>> mydict
{'a': 2, 'c': 1, 'b': 1, 'e': 5, 'd': 4}

 

update([other]):从其余dict更新字典。ip

>>> mydict
{'a': 2, 'c': 1, 'b': 1, 'e': 5, 'd': 4}
>>> mydcit
{'a': 1, 'c': 3, 'b': 2}
>>> mydict.update(mydcit)
>>> mydict
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> mydcit['f']=6
>>> mydict.update(mydcit)
>>> mydict
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'f': 6}

3.判断key是否在字典中ci

key in dict 与 dict.has_key()等价。或者返回keys()来判断。rem

>>> mydict
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'f': 6}
>>> 
>>> 'a' in mydict
True
>>> mydict.has_key('a')
True
>>> 'a' in mydict.keys()
True

4.删除元素get

  4.1 删除指定key的元素。

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

>>> mydict.pop('a',3)
1
>>> mydict.pop('g',3)
3

>>> mydict
{'b': 2, 'e': 5, 'd': 4, 'f': 6}
>>> del mydict['d']
>>> mydict
{'b': 2, 'e': 5, 'f': 6}

  4.2任意删除一个item

popitem ()

Remove and return an arbitrary (key, value) pair from the dictionary.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

 

>>> mydict.popitem()
('c', 3)

 

5. iter(d) 

Return an iterator over the keys of the dictionary. This is a shortcut for iterkeys().

 

 

 

>>> mydict
{'b': 2, 'e': 5, 'f': 6}
>>> mydict_iter=iter(mydict)
>>> mydict_iter
<dictionary-keyiterator object at 0x7fc1c20db578>
>>> mydict_iter.next()
'b'

6.获得指定key的value

   

>>> mydict
{'b': 2, 'e': 5, 'f': 6}
>>> mydict['b']
2
>>> mydict.get('b',4)
2

 

 
[('b', 2), ('e', 5), ('f', 6)]
>>> for i in mydict:
...     print i
... 
b
e
f

6.字典的shallow copy 与 deep copy

浅copy。

若是key对应的alue是整型,更改了以后,两个dict key对应的alues就是不同的

若是key对应的seuece类型,更改了以后,两个dict key 对应的alues是同样的。

由于若是是整形,指向的object的引用发生了变化。

而sequence对应的引用是不会发生变化的

 

 

[('b', 2), ('e', 5), ('f', 6)]>>> for i in mydict:...     print i... bef

相关文章
相关标签/搜索