bot 2
bot 2

Reputation: 1

sort dictionary with one other dictionary

So let's say I have a dic where keys are players and values are numbers of games.

dic1 = {player1: 100, 
        player2: 4, 
        player3: 400, 
        player4: 50
       }

Let's say now I will sort this dic

dic1_sorted = dict(sorted(dic1.items(), key=lambda item: item[1], reverse=True))

I will get this

dic1_sorted = {player3: 400,
               player1: 100,
               player4: 50,
               player2: 4
              }

So let's say I have a new dic where keys are players and values are win ratio.

dic2 = {player1: 1,
        player2: 0.5,
        player3: 0.7,
        player4: 0.2

dic2_sorted = {player3: 0.7,
               player1: 1,
               player4: 0.2,
               player2: 0.5
              }

How can I achieve dic2_sorted, which is sorted by dic1_sorted, without using panda and stuff like that and in an efficient way as possible?

Upvotes: 0

Views: 52

Answers (2)

zanga
zanga

Reputation: 719

You may want to use an OrderedDict

from collections import OrderedDict
keyorder = list(dic1_sorted.keys())
OrderedDict(sorted(dic2.items(), key=lambda i:keyorder.index(i[0])))

OrderedDict([('player3', 0.7),
             ('player1', 1),
             ('player4', 0.2),
             ('player2', 0.5)])

Upvotes: 1

Chris_Rands
Chris_Rands

Reputation: 41168

Look up the key from one dict with the other while sorting, I'm using - here to reverse the order, but reverse=True could be preferable (I converted your players to strings just for illustration)

dic1_sorted = {"player3": 400,
               "player1": 100,
               "player4": 50,
               "player2": 4
              }

dic2 = {"player1": 1,
        "player2": 0.5,
        "player3": 0.7,
        "player4": 0.2}

print(sorted(dic2.items(), key = lambda x: -dic1_sorted[x[0]]))
# [('player3', 0.7), ('player1', 1), ('player4', 0.2), ('player2', 0.5)]

Upvotes: 1

Related Questions