如何查找字典中的键是否已设置为非none值?
如果已经有一个值,我想增加值,否则设置为1:
my_dict = {}
if my_dict[key] is not None:
my_dict[key] = 1
else:
my_dict[key] += 1
如何查找字典中的键是否已设置为非none值?
如果已经有一个值,我想增加值,否则设置为1:
my_dict = {}
if my_dict[key] is not None:
my_dict[key] = 1
else:
my_dict[key] += 1
当前回答
这并不是直接回答这个问题,但对我来说,看起来您可能需要collections.Counter的功能。
from collections import Counter
to_count = ["foo", "foo", "bar", "baz", "foo", "bar"]
count = Counter(to_count)
print(count)
print("acts just like the desired dictionary:")
print("bar occurs {} times".format(count["bar"]))
print("any item that does not occur in the list is set to 0:")
print("dog occurs {} times".format(count["dog"]))
print("can iterate over items from most frequent to least:")
for item, times in count.most_common():
print("{} occurs {} times".format(item, times))
这就产生了输出
Counter({'foo': 3, 'bar': 2, 'baz': 1})
acts just like the desired dictionary:
bar occurs 2 times
any item that does not occur in the list is set to 0:
dog occurs 0 times
can iterate over items from most frequent to least:
foo occurs 3 times
bar occurs 2 times
baz occurs 1 times
其他回答
有点晚了,但应该有用。
my_dict = {}
my_dict[key] = my_dict[key] + 1 if key in my_dict else 1
要回答“我如何才能知道字典中给定的索引是否已经被设置为非none值”的问题,我更喜欢这样:
try:
nonNone = my_dict[key] is not None
except KeyError:
nonNone = False
这符合已经引用的EAFP概念(请求原谅比请求许可更容易)。它还避免了字典中的重复键查找,因为它会在my_dict和my_dict[key]不是None的key中查找,如果查找是昂贵的,这是有趣的。
对于您提出的实际问题,即增加int值(如果存在),或将其设置为默认值(否则),我还建议使用
my_dict[key] = my_dict.get(key, default) + 1
正如安德鲁·威尔金森的回答。
如果要在字典中存储可修改的对象,还有第三种解决方案。一个常见的例子是multimap,在其中存储键的元素列表。在这种情况下,你可以使用:
my_dict.setdefault(key, []).append(item)
如果字典中不存在forkey的值,setdefault方法将其设置为setdefault的第二个参数。它的行为就像一个标准的my_dict[key],返回键的值(可能是新设置的值)。
您正在寻找collections.defaultdict(适用于Python 2.5+)。这
from collections import defaultdict
my_dict = defaultdict(int)
my_dict[key] += 1
会做你想做的事。
对于常规的Python字典,如果给定的键没有值,则在访问字典时不会得到None——会引发KeyError。所以如果你想使用一个普通的字典,而不是你的代码,你会使用
if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1
我个人喜欢使用setdefault()
my_dict = {}
my_dict.setdefault(some_key, 0)
my_dict[some_key] += 1
这并不是直接回答这个问题,但对我来说,看起来您可能需要collections.Counter的功能。
from collections import Counter
to_count = ["foo", "foo", "bar", "baz", "foo", "bar"]
count = Counter(to_count)
print(count)
print("acts just like the desired dictionary:")
print("bar occurs {} times".format(count["bar"]))
print("any item that does not occur in the list is set to 0:")
print("dog occurs {} times".format(count["dog"]))
print("can iterate over items from most frequent to least:")
for item, times in count.most_common():
print("{} occurs {} times".format(item, times))
这就产生了输出
Counter({'foo': 3, 'bar': 2, 'baz': 1})
acts just like the desired dictionary:
bar occurs 2 times
any item that does not occur in the list is set to 0:
dog occurs 0 times
can iterate over items from most frequent to least:
foo occurs 3 times
bar occurs 2 times
baz occurs 1 times