This is a test version of Biostars. For the public version, visit https://www.biostars.org.
sort dictionary in python?

I have a dictionary:

d = {'b':1, 'a':3, 'aa':12,'c':24, 'bb':31,'abc':123}

I have a list containing keys:

l = ['a','c','b','abc','bb','aa']

How to sort d1 based on l in python (or pandas)? I want the keys in d1 to be sorted in the order in l.

d_sorted = {'a':3,'c':24, 'b':1,'abc':123, bb':31,'aa':12'}

Thank you.

python

Hello xupbuy!

We believe that this post does not fit the main topic of this site.

This is a pure python question, which is better asked e.g. on stackoverflow.

See also:

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

sorry. I'll try stackoverflow.

Incidentally, dicts cannot be ordered in python. You will want to look at the OrderedDict construct from the collections module.

Thank you for the reply.

0 answers

No answers yet.

Log in to answer this question.