0

I have a dict of data-frames like the following:

symbols ={BTC: DF, ETH: DF, DOGE:df}

where each DF looks like this.

index   price   price_change
0        10.    0
1        15     50
2        30     100
3        10     -50

I am trying to sort the dict by the price_change in the last row.

  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Michael Delgado Sep 14 '21 at 22:46

1 Answers1

1

You could figure out the sorting of the keys by using a lambda function on sorted, which gets the last price change per df. Using reverse=True would sort them in the order I believe you are looking for. Then it's a matter of reconstructing a new dict in that order using dict comprehension.

symbols = {
    'BTC':pd.DataFrame({
        'index': {0: 0, 1: 1, 2: 2, 3: 3},
        'price': {0: 10.0, 1: 15.0, 2: 30.0, 3: 10.0},
        'price_change': {0: 0, 1: 50, 2: 100, 3: -50}}),
    'ETH':pd.DataFrame({
        'index': {0: 0, 1: 1, 2: 2, 3: 3},
        'price': {0: 10.0, 1: 15.0, 2: 30.0, 3: 10.0},
        'price_change': {0: 0, 1: 50, 2: 100, 3: -10}})
}

{k:symbols[k] for k in sorted(symbols, key=lambda x: symbols[x].price_change.iloc[-1], reverse=True)}

Output

{'ETH':    index  price  price_change
 0      0   10.0             0
 1      1   15.0            50
 2      2   30.0           100
 3      3   10.0           -10,
 'BTC':    index  price  price_change
 0      0   10.0             0
 1      1   15.0            50
 2      2   30.0           100
 3      3   10.0           -50}
Chris
  • 15,819
  • 3
  • 24
  • 37