Home > OS >  Python: How to select and then compare and filter certain values in a dict?
Python: How to select and then compare and filter certain values in a dict?

Time:08-13

I have a dict which looks like this:

{
    'Amathus': [datetime.date(2022, 8, 10), datetime.time(1, 30), 'Wroclaw', Decimal('3.75'), 33.91], 
    'Falesia': [datetime.date(2022, 8, 10), datetime.time(1, 30), 'Wroclaw', Decimal('4.00'), 21.46], 
    'Diamond': [datetime.date(2022, 8, 10), datetime.time(1, 30), 'Posznan', Decimal('4.50'), 40.24], 
    'Kid': [datetime.date(2022, 8, 10), datetime.time(1, 30), 'Posznan', Decimal('4.50'), 42.24]
}

and so on.

I now want to select every Key that has the value "Wroclaw", these keys for the last value (74,14 for example) and only return the highest 3 keys with all values attached.

My try so far:

I get all the keys with this:

getkeys = [k for k, v in mydict.items() if city in v] #city is a variable, containing "Wroclaw"
newdict = {}
for k in getkeys :
    aupdate = {k :finaldict2[k]}
    newdict.update(aupdate)
sorteddict = sorted(newdict, key=newdict.get, reverse=True)

So far, so good - I now have the keys in the sorted order in a list. Now I could use sth like this to print the 3 highest values:

    counting = 0
    while counting <= 2:
        testvalue = newdict[sorteddict[counting]]
        print(sorteddict[counting],testvalue)
        counting  = 1

But this feels so clonky and just not like the best solution, but this is a far as I come right now.

So how to improve this approach further? Any advice is appreciated :D

CodePudding user response:

You don't need the sorted list of keys.

result = sorted(newdict.items(), key=lambda x: x[1], reverse=True)[:3]

This returns a list of (key, value) tuples.

  • Related