AndrewRoj
AndrewRoj

Reputation: 97

How to perform an assertion to verify an item is in a list of dicts in Python

I am trying to figure out how to do an assertion to see if a number exists in a list.

So my list looks like:

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'}]

Now I am trying to iterate through the list like:

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

I am somehow only getting the first number returned for "value" i.e. 4.21

Upvotes: 0

Views: 1269

Answers (1)

Selcuk
Selcuk

Reputation: 59315

You have two problems as other commenters pointed out. You compare the wrong data types (str against Decimal, or after your edit, float against Decimal) and you also terminate on first failure. You probably wanted to write:

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

This will extract the value of the "value" key from each sub-dictionary inside the list and search for Decimal('2.21') in them.

Upvotes: 5

Related Questions