“Collections.DefaultDict (set)” Code-Antworten

Aus den Sammlungen importieren Sie Standarddict

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
Unusual Unicorn

Collections.DefaultDict (set)

defaultdict means that if a key is not found in the dictionary,
then instead of a KeyError being thrown, a new entry is created. 
The type of this new entry is given by the argument of defaultdict.

For example:

somedict = {}
print(somedict[3]) # KeyError

someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0

>>> from collections import defaultdict
Concerned Crab

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen