Python中的dicts列表中提供了如何执行断言来验证项



我正试图弄清楚如何断言列表中是否存在数字。

所以我的列表看起来像:

data = [{'value': Decimal('4.21'), 'Type': 'sale'},
{'value': Decimal('84.73'), 'Type': 'sale'},
{'value': Decimal('70.62'), 'Type': 'sale'},
{'value': Decimal('15.00'), 'Type': 'credit'},
{'value': Decimal('2.21'), 'Type': 'credit'},
{'value': Decimal('4.21'), 'Type': 'sale'},
{'value': Decimal('84.73'), 'Type': 'sale'},
{'value': Decimal('70.62'), 'Type': 'sale'},
{'value': Decimal('15.00'), 'Type': 'credit'},
{'value': Decimal('2.21'), 'Type': 'credit'}]

现在我正在尝试迭代列表,如:

for i in data:
s = i['value']
print(s)
assert 2.21 in i['value'], "Value should be there"

不知怎的,我只得到了";值";即4.21

正如其他评论者指出的那样,您有两个问题。比较错误的数据类型(strDecimal,或者在编辑后,floatDecimal(,第一次失败时也会终止。你可能想写:

assert Decimal('2.21') in (d["value"] for d in data)

这将从列表中的每个子字典中提取"value"关键字的值,并在其中搜索Decimal('2.21')

最新更新