如何查找字典中的键是否已设置为非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[some_key] = my_dict.get(some_key, 0) + 1

字典有一个函数get,它接受两个参数——你想要的键和一个默认值(如果它不存在的话)。我更喜欢这个方法而不是defaultdict,因为您只想处理键在这一行代码中不存在的情况,而不是到处都不存在。

您尝试执行此操作的方法称为LBYL(三思而后行),因为您在尝试增加值之前要检查条件。

另一种方法被称为EAFP(请求原谅比请求许可更容易)。在这种情况下,您只需尝试操作(增加值)。如果失败,则捕获异常并将值设置为1。这是一种稍微更python化的方式(IMO)。

http://mail.python.org/pipermail/python-list/2003-May/205182.html

这并不是直接回答这个问题,但对我来说,看起来您可能需要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

我正在寻找它,没有在网上找到它,然后尝试我的运气与尝试/错误,找到了它

my_dict = {}

if my_dict.__contains__(some_key):
  my_dict[some_key] += 1
else:
  my_dict[some_key] = 1