Home > Software engineering >  Select second item in list where value in dictionary follows condition
Select second item in list where value in dictionary follows condition

Time:09-15

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.

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

Did you try doing it like this.

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