Luiz Scheuer
Luiz Scheuer

Reputation: 335

Select second item in list where value in dictionary follows condition

I have the following list of dictionaries:

l = [{'cycleIndex': 1, 'amount': 100},
     {'cycleIndex': 1, 'amount': 200},
     {'cycleIndex': 2, 'amount': 1000},
     {'cycleIndex': 2, 'amount': 2000}]

I want to print out 200 and 2000 which are the values in the second dictionary "where" cycleIndex is repeated.

I basically want to select a specific value for a given element (which are dictionaries in this case, hence "value") in a list, filtering by another value within that dictionary.

Upvotes: 0

Views: 35

Answers (3)

crunker99
crunker99

Reputation: 371

This will keep track of the indexes, anything after the first occurrence of an index will be printed out.

seen_indexes = set()
for d in l:
    index, amount = d['cycleIndex'], d['amount']
    if index not in seen_indexes:
        seen_indexes.add(index)
    else:
        print(amount)

Upvotes: 1

eshirvana
eshirvana

Reputation: 24593

you can use pandas :

import pandas as pd

output = pd.DataFrame(l).drop_duplicates(subset='cycleIndex',keep='last').to_json(orient='records')

output :

>> [{"cycleIndex":1,"amount":200},{"cycleIndex":2,"amount":2000}]

Upvotes: 1

Pw Wolf
Pw Wolf

Reputation: 350

Did you try doing it like this.

for i in l:
    if i["amount"] == 200 or i["amount"] == 2000:
        # Do something

Upvotes: 0

Related Questions