this article illustrates the way Python maps keys to multiple values in a dictionary. 分享给大家供大家参考,具体如下:

问题:一个能将键(key)映射到多个值的字典(即所谓的一键多值字典[multidict])

解决方案:如果想让键映射到多值,需要将这多个值保持到另一个容器如列表或集合中;

 >>> d={'a':[1,2,3],'b':[4,5]} >>> d {'b': [4, 5], 'a': [1, 2, 3]} >>> e={'a':{1,2,3,3},'b':{4,5}} >>> e {'b': {4, 5}, 'a': {1, 2, 3}} >>> f={'a':[1,2,3,3],'b':[4,5]} >>> f {'b': [4, 5], 'a': [1, 2, 3, 3]} >>>  

更方便的创建这样的字典是利用collections模块中的defaultdict类。 One of the features of defaultdict is that it automatically initializes the first value to the dictionary, so only the element is added. For example:

 from collections import defaultdict d=defaultdict (list) # create a key value dictionary, key value is a list type d['a'].append (1) d['a'].append (2) d['a'].append (2) d['b'].append (4) c=defaultdict (set) # create a key value dictionary, key value is a set type c['a'].add (1) c['a'].add (2) c['a'].add (2) c['b'].add (4) print ('key value list type Dictionary: ', d) print ('key value set type Dictionary:', c) 
 > > > RESTART = ============================= ran > > > key value type list Dictionary: defaultdict (< class,'list'> {'b': [4],'a': [1, 2, 2]}) key value set is a type of Dictionary: defaultdict (< class,'set'> {'b': {4}: {1,'a', 2}}) > > > 

needs to pay attention to defaultdict. It will automatically create dictionary table items for later visit (even if these items are not currently found in the dictionary).

if you want to cancel the function, can be in an ordinary dictionary called setdefault () method to replace, for example:

 d={} # an ordinary dictionary d.setdefault ('a', []).Append (1) d.setdefault ('a', []).Append (2) d.setdefault ('a',.Append (2) []) d.setdefault ('b', []).Append (4) > > > 

key value list

 {'a'type Dictionary:: [1, 2, 2],'b': [4]} 

added:

to build a key value a dictionary is very easy, but if you try to first a value initialization operation, this will become very messy, if you use the defaultdic code more concise:

: [22,44],'b':

 pairs={'a' [88]} d=defaultdict (list) for key, value in (pairs.items): d[key].append (value) print (d) > > Defaultdict (< > class;'list'> {'a': [[22, 44]],'b', [[88]]}) > > > 

("Python Cookbook")

more Python on the relevant content of interested readers can view this topic: "Python data structure and algorithm tutorial ", "Python ", summarizes the skills in the use of function "Python " string manipulation skills summary, "Python into the door and advanced classic tutorial" Python

operation skills summary" the hope for all Python programming help.

you might be interested in this article: