for 循环、dict.setdefault(key,[]).append(value)、result=defaultdict(list)

Using a variety of data processing for loop

In [24]:
words =['apple','pare','banana','and','peach']
 
 
In [57]:
byletter = {}
for word in words:
    letter=word[0]
    if letter  in byletter:
        byletter[letter].append(word)
    else:
        byletter[letter]=[word]
 
In [58]:
byletter
 
 
Out[58]:
{'a': ['apple', 'and'], 'p': ['pare', 'peach'], 'b': ['banana']}
 

dict.setdefault(key,[]).append(value)

setdefault dictionary object is an instance method, the receiving two parameters, and similar usage dictionary get method, but more powerful than get. It can be set to a default value for the dictionary key (if the key is not in the dictionary of the time) to set default values ​​get method does not change the original dictionary, and the default value setdefault setting will change the value of the original dictionary.

In [41]:
by_letters={}
for word in words:
    letter=word[0]
    by_letters.setdefault(letter,[]).append(word)
 
 
In [43]:
  by_letters
 
 
Out[43]:
{'a': ['apple', 'and'], 'p': ['pare', 'peach'], 'b': ['banana']}
In [59]:
 
data=[('p',1),('p',2),('p',3),('h',4),('h',5),('h',6)]
 
result=defaultdict(list)

defaultdict a plant belonging to the function of the collections module for building an object dictionary, a receiving function (callable) object as a parameter. What type parameter returns, key value that corresponds to what type.

In [66]:
  from collections import defaultdict
results=defaultdict(list)
data=[('p',1),('p',2),('p',3),('h',4),('h',5),('h',6)]
for (key,value) in data:
    results[key].append(value)
 
 
In [67]:
results
 
 
Out[67]:
defaultdict(list, {'p': [1, 2, 3], 'h': [4, 5, 6]})

Guess you like

Origin www.cnblogs.com/liyun1/p/11248123.html