我想知道,我如何检查字典中是否存在某个键。我正在使用以下代码:用if语句添加不存在的字典关键字(Python)
my_dict = {};
my_list = ["one", "two", "three", "one"];
for i in my_list:
if i in my_dict:
continue;
else:
my_dict[i] = 0;
但我想在if语句中使用“NOT”运算符从其中删除else运算符。
我想知道,我如何检查字典中是否存在某个键。我正在使用以下代码:用if语句添加不存在的字典关键字(Python)
my_dict = {};
my_list = ["one", "two", "three", "one"];
for i in my_list:
if i in my_dict:
continue;
else:
my_dict[i] = 0;
但我想在if语句中使用“NOT”运算符从其中删除else运算符。
这应该工作:
my_dict = {}
my_list = ["one", "two", "three", "one"]
for i in my_list:
if i not in my_dict:
my_dict[i] = 0
因此,如果该键不存在于字典它只会增加值。
你可以试试:
if i not in my_dict:
....
my_dict = dict.fromkeys(my_list, 0)
谢谢,它真的帮了我。 –
我试过用“!”在if语句中的运算符并且它不起作用,我忘记了运算符“not”:((。 –