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

Method fromkeys

recipes/Python/578611_Bag_class/recipe-578611.py:41–60  ·  view source on GitHub ↗

Class method which creates bag from iterable adding optional count for each item. >>> b = Bag({'b': 2, 'c': 1, 'a': 3}) >>> b2 = Bag.fromkeys(['a', 'b', 'c', 'b', 'a', 'a']) >>> b3 = Bag.fromkeys("abacab") >>> assert b == b2 == b3 >>> word_count = Bag.fromke

(cls, iterable, count=1)

Source from the content-addressed store, hash-verified

39 self[key] += count
40
41 def fromkeys(cls, iterable, count=1):
42 """Class method which creates bag from iterable adding optional count for each item.
43
44 >>> b = Bag({'b': 2, 'c': 1, 'a': 3})
45 >>> b2 = Bag.fromkeys(['a', 'b', 'c', 'b', 'a', 'a'])
46 >>> b3 = Bag.fromkeys("abacab")
47 >>> assert b == b2 == b3
48
49 >>> word_count = Bag.fromkeys("how much wood could a wood chuck chuck".split())
50 >>> print(word_count)
51 {'a': 1, 'chuck': 2, 'could': 1, 'how': 1, 'much': 1, 'wood': 2}
52
53 An optional count can be specified. Count added each time item is encountered.
54 >>> print(Bag.fromkeys("abacab", 5))
55 {'a': 15, 'b': 10, 'c': 5}
56 """
57 b = cls()
58 for key in iterable: #could just return b.__iadd__(iterable, count)
59 b[key] += count #perhaps slower than necessary but will simplify derived classes that override __setitem__()
60 return b
61
62 fromkeys = classmethod(fromkeys)
63

Callers

nothing calls this directly

Calls 1

clsClass · 0.50

Tested by

no test coverage detected