Select second item in list where value in dictionary follows condition

Question:

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.

Asked By: Luiz Scheuer

||

Answers:

Did you try doing it like this.

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

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}]
Answered By: eshirvana

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)
Answered By: crunker99
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.