This article mainly introduces the Python dict dictionary structure operation method learning notebook. The dictionary operation is the basic knowledge in the Python getting started learning. For more information, see
I. Basic dictionary Methods
1. Create a dictionary
1) Create an empty dictionary
>>> dict1={} >>> dict2=dict() >>> dict1,dict2 ({}, {})
2) initialize a new value
>>> dict1={1:'a',2:'b',3:'c'} >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
3) Use tuples
>>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
2. Obtaining Method
1) get (key) obtains the value corresponding to a key from the dictionary and returns the value
>>> dict1={1:'a',2:'b',3:'c'} >>> dict1.get(1) 'a'
If the dictionary does not exist, a NoneType is returned.
>>> type(dict1.get(4))
If the key value does not exist and another value is specified
>>> dict1.get(4,'not found') 'not found'
2). keys () obtains all the key values in the dictionary and returns a list.
>>> dict1.keys() [1, 2, 3]
3). values () corresponds to the keys () method, and the list of all values in the returned dictionary
>>> dict1.values() ['a', 'b', 'c']
4) items () returns a key, value, and corresponding tuples.
>>> dict1.items() [(1, 'a'), (2, 'b'), (3, 'c')]
5) iterkeys (), itervalues (), and iteritems () also obtain all the key, value, (key, value) ancestor respectively, but not the return list, but an iterator.
>>> for key in dict1.iterkeys(): print key 1 2 3
3. Set the dictionary Value
1) the direct method is
>>> dict1[4]='d' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
However, this method overwrites the original value if the key value I want to add is already in the dictionary.
>>> dict1[4]='e' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e'}
2) the advantage of setdefault (key, value) is that if the inserted key does not exist in the dictionary, the dictionary is inserted and the value is returned. Otherwise, the value exists in the dictionary, the returned value will not overwrite the existing value.
>>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e'} >>> dict1.setdefault(5,'f') 'f' >>> dict1.setdefault(5,'g') 'f' >>> dict1 {1: 'a', 2: 'b', 3: 'c', 4: 'e', 5: 'f'}
4. delete a dictionary
1) pop (key) deletes an item of the specified key and returns a value of the deleted item. If no value exists, an exception is thrown. Therefore, when using this method, you must determine whether the key exists or catch this exception.
>>> def pop_key(d,key): try: d.pop(key) print "sucess" except: print "key is not in dict" >>> dict1 {1: 'a', 2: 'b'} >>> pop_key(dict1,3) key is not in dict
Or
>>> def sub_dict2(d,key): if d.has_key(key): d.pop(key) print "sucess" else:print "key is not in dict" >>> pop_key(dict1,3) key is not in dict
The has_key (key) Here is used to determine whether the key exists in the dictionary. Of course, the key in d can also be used instead.
2) popitem () is similar to pop (), but it only deletes a (key, value) tuples.
Using the above method, you can use some advanced usage
A. Create A dictionary using two lists. The first list is all keys, and the second list is all values.
>>> list1=[1,2,3] >>> list2=['a','b','c'] >>> dict1=dict(zip(list1,list2)) >>> dict1 {1: 'a', 2: 'b', 3: 'c'}
B. Find a dictionary sub-dictionary
>>> dict1 {1: 'a', 2: 'b', 3: 'c'} >>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) >>> dict1 {1: 'a', 2: 'b', 3: 'c'} >>> subkeys=[1,3] >>> def sub_dict(d,subkeys): return dict([(k,d.get(k)) for k in subkeys if k in d]) >>> print sub_dict(dict1,subkeys) {1: 'a', 3: 'c'}
C. Reverse dictionary, that is, the key is changed to the value of the new dictionary, and the value is changed to the key of the new dictionary. (Note that if the value is repeated, only one dictionary will be retained after reverse conversion.
>>> def invert_dict(d): return dict([(k,v) for v,k in d.iteritems()]) >>> print invert_dict(dict1) {'a': 1, 'c': 3, 'b': 2} >>>
5. other basic methods
1) has_key (key) determines whether the key is in the dictionary
2) copy () returns a copy of the Dictionary (this copy is a light copy)
>>> d2={1:[1],2:[2],3:[3]} >>> d3=d2.copy() >>> d3[1].append(4) >>> d2[1] [1, 4]
Copy. deepcopy (a) is required for deep replication)
>>> d2={1:[1],2:[2],3:[3]} >>> import copy >>> d3=copy.deepcopy(d2) >>> d3[1].append(4) >>> print d2[1] , d3[1] [1] [1, 4]
3) clear () clear dict
4) update (d) uses a dictionary to merge with the new dictionary.
>>> dict1={1: 'a', 2: 'b', 3: 'c'} >>> dict2={1:'x',4:'y'} >>> dict1.update(dict2) >>> dict1 {1: 'x', 2: 'b', 3: 'c', 4: 'y'} >>>
Ii. Traversal
Dictionary traversal methods
1. directly use dict
>>> d {'a': 'aa', 'c': 'cc', 'b': 'bb'} >>> for i in d: print i,d[i] a aa c cc b bb
2. Use items ()
>>> for i,v in d.items(): print i,v a aa c cc b bb
Of course.
>>> for (i,v) in d.items(): print i,v a aa c cc b bb
I was impressed by an article that compares the efficiency of the two methods (with and without parentheses), saying that when the dictionary size is below 200, there are Parentheses faster, and when the dictionary size is above 200, the speed is faster without parentheses, And I didn't test it either.
3. iteritems ()
(I think it is a good method)
>>> for k,v in d.iteritems(): print k,v a aa c cc b bb
There are other traversal methods, but I think these three are enough.
Iii. Advanced usage
1. One-click multi-value
In general, dictionaries are mapped to one, but if we need a one-to-many ing, such as a book, we need to count the number of pages of some words. You can use list as the value of dict. You can do this by using the setdefault () method.
>>> d={'hello':[1,4,9],"good":[1,3,6]} >>> d {'good': [1, 3, 6], 'hello': [1, 4, 9]} >>> d.setdefault('good',[]).append(7) >>> d {'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} >>> d.setdefault('bad',[]).append(2) >>> d {'bad': [2], 'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} >>>
Of course, if you write a function, you can use it more conveniently,
We can also use set to replace list.
>>> def addFunc(d,word,pag): d.setdefault(word,set()).add(pag) >>> d={'hello':set([1,4,9]),"good":set([1,3,6])} >>> addFunc(d,'hello',8) >>> d {'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])} >>> addFunc(d,'bad',8) >>> d {'bad': set([8]), 'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])}
2. Use the dictionary to complete the simple factory Mode
Dictionary values are not only common strings, values, but also classes and methods. For example, we can implement the simple factory mode.
>>> class cat(object): def __init__(self): print 'cat init' >>> class dog(object): def __init__(self): print 'dag init' >>> d={'cat':cat,'dog':dog} >>> def factoryFunc(d,name): if name in d: return d[name]() else: raise Exception("error") >>> cat=factoryFunc(d,'cat') cat init
Another example is to use variables to control the executed functions.
>>> def deal_cat(): print 'cat run!!' >>> def deal_dog(): print 'dag run!!' >>> d={'cat':deal_cat ,'dog':deal_dog } >>> animal='cat' >>> d[animal]() cat run!!