Python dict dictionary structure operation method

Source: Internet
Author: User
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 about how to learn about Python dict dictionary structure, see the next article.

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


For more articles on how to operate Python dict dictionary structures, refer to PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.