def __init__(self, items = None):
"""Create a dictionary from iters.
If items can't be fed to a dictionary, it will be interpreted as a
collection of keys, and each value will default to value 1/n. Otherwise,
the values are normalized to sum to one. Raises ValueError if
some values are not numbers or are negative.
Arguments:
- `items`: argument with which to make dictionary
"""
if items is None: return dict.__init__(self)
try:
# can fail if items is not iterable or not full of size 2 items:
dict.__init__(self, items)
except TypeError:
try:
# Let's assume items is a finite iterable full of keys
vals = [1/len(items)] * len(items)
except TypeError:
# Apparently items has no length -- let's take it as the only
# key and put all the probability on it.
dict.__init__(self, (items, 1))
else:
# if items has a length, it can be iterated through with zip
dict.__init__(self, zip(items, vals))
else:
# we've successfully made dic from key, value pairs in items, now let's
# normalize the dictionary, and check the values
for v in self.values():
if not isinstance(v, Real):
raise TypeError("Values must be nonnegative real numbers so I " +
"can properly normalize them. " + str(v) + " is not.")
elif v < 0:
raise ValueError("Values must be nonnegative, unlike " + str(v))
tot = sum(self.values())
for k, v in self.items(): self[k] = v/tot
评论列表
文章目录