user7179686
user7179686

Reputation:

Order by value in dictionary

I'm just practising with python. I have a dictionary in the form:

my_dict = [{'word': 'aa', 'value': 2}, 
           {'word': 'aah', 'value': 6}, 
           {'word': 'aahed', 'value': 9}]

How would I go about ordering this dictionary such that if I had thousands of words I would then be able to select the top 100 based on their value ranking? e.g., from just the above example:

scrabble_rank = [{'word': 'aahed', 'rank': 1},
                 {'word': 'aah', 'rank': 2}, 
                 {'word': 'aa', 'rank': 3}]

Upvotes: 0

Views: 70

Answers (4)

JkShaw
JkShaw

Reputation: 1947

You can use heapq:

import heapq

my_dict = [{'word': 'aa', 'value': 2}, 
           {'word': 'aah', 'value': 6}, 
           {'word': 'aahed', 'value': 9}]

# Select the top 3 records based on `value`
values_sorted = heapq.nlargest(3, # fetch top 3
                               my_dict, # dict to be used
                               key=lambda x: x['value']) # Key definition
print(values_sorted)
[{'word': 'aahed', 'value': 9}, {'word': 'aah', 'value': 6}, {'word': 'aa', 'value': 2}]

Upvotes: 0

jlandercy
jlandercy

Reputation: 11097

Using Pandas Library:

import pandas as pd

There is this one-liner:

scrabble_rank = pd.DataFrame(my_dict).sort_values('value', ascending=False).reset_index(drop=True).reset_index().to_dict(orient='records')

It outputs:

[{'index': 0, 'value': 9, 'word': 'aahed'},
 {'index': 1, 'value': 6, 'word': 'aah'},
 {'index': 2, 'value': 2, 'word': 'aa'}]

Basically it reads your records into a DataFrame, then it sort by value in descending order, then it drops original index (order), and it exports as records (your previous format).

Upvotes: 0

nikpod
nikpod

Reputation: 1278

Is this what you are looking for:

scrabble_rank = [{'word':it[1], 'rank':idx+1} for idx,it in enumerate(sorted([[item['value'],item['word']] for item in my_dict],reverse=True))]

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600059

Firstly, that's not a dictionary; it's a list of dictionaries. Which is good, because dictionaries are unordered, but lists are ordered.

You can sort the list by the value of the rank element by using it as a key to the sort function:

scrabble_rank.sort(key=lambda x: x['value'])

Upvotes: 3

Related Questions