Megha Aggarwal
Megha Aggarwal

Reputation: 101

Sort dictionary in Python based on other dictionary keys

I have two dictionary x and y

Input -

x = {"a":1, "b": 2, "c:3", "d":5}

y = {"c":3000, "a":10000}

Expected Output -

y = {"a":10000, "c":3000}

The orders of key of dictionary y should be based on order of keys in x dictionary These two dictionary are coming from different source.

Edit -y will have only keys that are already present in x, Also the values of key in y will be different than x

Any help would be much appreciated. Thanks!

Upvotes: 0

Views: 246

Answers (2)

chatax
chatax

Reputation: 998

Iterate over the keys and values of x and check if the key exists within y.

y = {key: y[key] for key, value in x.items() if key in y}

Upvotes: 1

napuzba
napuzba

Reputation: 6288

This will work only in the recent versions of python

y = { key: y[key] for key in x if key in y}

For earlier versions you can check collections.OrderedDict

Upvotes: 3

Related Questions