[英]Adding not existing key to dictionary with if statement (Python)
I'd like to know, how I could check if a key already exists in a dictionary. 我想知道如何检查字典中是否已存在键。 I am using the following code:
我正在使用以下代码:
my_dict = {};
my_list = ["one", "two", "three", "one"];
for i in my_list:
if i in my_dict:
continue;
else:
my_dict[i] = 0;
but I'd like to use "NOT" operator in if statement to remove else operator from it. 但我想在if语句中使用“ NOT”运算符从其中删除else运算符。
This should work: 这应该工作:
my_dict = {}
my_list = ["one", "two", "three", "one"]
for i in my_list:
if i not in my_dict:
my_dict[i] = 0
Thus, it will only add the value if the key doesn't exist in the dictionary. 因此,仅当字典中不存在键时,才会添加值。
You can try: 你可以试试:
if i not in my_dict:
....
my_dict = dict.fromkeys(my_list, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.