MCPcopy Create free account
hub / github.com/ActiveState/code / fromkeys

Method fromkeys

recipes/Python/579113_defdict/recipe-579113.py:88–109  ·  view source on GitHub ↗

Create dictionary from iterable with optional default value. One can initialize defdict with a sequence of keys. The dictionary values of the keys will be determined by the default value, if given, otherwise defaults to None. >>> print DefDict.fromkeys(["apple", "ba

(cls, iterable, default=None, collision=_OVERWRITE_)

Source from the content-addressed store, hash-verified

86 self.setdefault(key, value, collision)
87
88 def fromkeys(cls, iterable, default=None, collision=_OVERWRITE_):
89 """Create dictionary from iterable with optional default value.
90
91 One can initialize defdict with a sequence of keys.
92 The dictionary values of the keys will be determined by the default value,
93 if given, otherwise defaults to None.
94
95 >>> print DefDict.fromkeys(["apple", "banana", "carrot"])
96 {'apple': None, 'banana': None, 'carrot': None}
97 >>> dd = DefDict.fromkeys(range(4), 0) #initialize with values = 0
98 >>> print dd
99 {0: 0, 1: 0, 2: 0, 3: 0}
100 >>> dd.update([0]) #default value retained?
101 >>> print dd[0] #Yes if output is 1
102 1
103 >>> print DefDict.fromkeys("abacab", 1, _ADD_)
104 {'a': 3, 'b': 2, 'c': 1}
105 """
106 dd = cls(default=default)
107 for key in iterable:
108 dd.setdefault(key, default, collision)
109 return dd
110
111 fromkeys = classmethod(fromkeys)
112

Callers 1

_make_constantsFunction · 0.45

Calls 2

clsClass · 0.50
setdefaultMethod · 0.45

Tested by

no test coverage detected