I have this:
我有这个:
list_name = [0, 1, 2, 3]
list_name[0] = {}
list_name[0]['test'] = 'any value'
I want to know if a key of the list exists or not. Usually I use:
我想知道列表中的密钥是否存在。通常我用:
if 3 not in list_name:
print("this doesn't exist")
else:
print("exists")
And testing this for example for number 3 is working. It says "exists". If I check for number 999 is working, it says "this doesn't exist".
例如,对3号进行测试是有效的。它说“存在”。如果我检查号码999是否有效,则说“这不存在”。
The problem is that it is not working for 0. As you can see, 0 value in the list has a dictionary. And I need to check if 0 exists or not in the list (doesn't matter if it has a dictionary or not). How to achieve this? Using python3, thank you.
问题是它不适用于0.正如您所看到的,列表中的0值具有字典。我需要检查列表中是否存在0(如果它有字典则无关紧要)。怎么做到这一点?使用python3,谢谢。
2 个解决方案
#1
1
Use try
except
for check index is exists or not
使用try除了检查索引是否存在
try:
if list_name[6]:
print("exists")
except IndexError:
print("this doesn't exist")
Output
this doesn't exist
这不存在
#2
2
If element 0
exists in the list, then the length of the list must be greater than zero. So you could use:
如果列表中存在元素0,则列表的长度必须大于零。所以你可以使用:
if len(list_name) > 0:
print("0 exists")
else:
print("0 does not exist")
As a side note, {}
is a dictionary, not an array.
作为旁注,{}是字典,而不是数组。
#1
1
Use try
except
for check index is exists or not
使用try除了检查索引是否存在
try:
if list_name[6]:
print("exists")
except IndexError:
print("this doesn't exist")
Output
this doesn't exist
这不存在
#2
2
If element 0
exists in the list, then the length of the list must be greater than zero. So you could use:
如果列表中存在元素0,则列表的长度必须大于零。所以你可以使用:
if len(list_name) > 0:
print("0 exists")
else:
print("0 does not exist")
As a side note, {}
is a dictionary, not an array.
作为旁注,{}是字典,而不是数组。