dict

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

>>> 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,创建dict

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

3.更新字典

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

>>> 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值

>>> 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更新字典。

>>> 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是否在字典中

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

>>> 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.删除元素

  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

原文地址:https://www.cnblogs.com/caizhenzhen/p/5094640.html