0

I have list containing multiple dictionary objects. I want to detect when there is no value in a specific key-value pair. When the value exists it is numeric. When the value does not exist, it appears to be is an empty string (judging from the Stack Data).

Initially I tried:

for dictionary_item in row_list:
    if dictionary_item['targetkey'] == '':
        #do stuff

This throws an "unsupported operand type" error when it encounters a number.

The value in the key-value pair may be either a number or an empty string. What is a good test expression for this scenario?

4

2 回答 2

2

我个人会使用isinstance

if isinstance(dictionary_item['targetkey'], float):

即使数字是0.0,这也将起作用,False在 Python 中计算为 。

请看下面的演示:

>>> bool(0.0)
False
>>> isinstance(0.0, float)
True
>>> isinstance(10.0, float)
True
>>> isinstance('', float)
False
>>>
于 2013-11-12T19:21:44.143 回答
1

试试这个,只要字典中的值不包括零,它就可以工作:

if dictionary_item['targetkey']:
    # do stuff

以上将检查是否dictionary_item['targetkey']为非空、非空和非零。如果零字典中的有效值,则执行以下操作:

if dictionary_item['targetkey'] or dictionary_item['targetkey'] == 0:
    # do stuff
于 2013-11-12T19:20:51.923 回答