1

I have python dictionary combination of lists and string.

e.g

dic = {"a": "11","c": [1,3,4], "b": [1,2,3], "g": "a"}

I want to sort it by datatype.

like

dic = {"a": "11", "g": "a", "c": [1,3,4], "b": [1,2,3]}
1
  • 1
    Dictionaries don't have order! Use collections.OrderedDict, if you wish Commented Sep 21, 2013 at 10:37

1 Answer 1

5

Dicts are inherently orderless, so you can only get a sorted list out of the dictionary. If you wish to get a list of key/value pairs, sorted by the type of the values, you can do it like this:

sorted(dic.items(), key=lambda pair: type(pair[1]), reverse=True)

This will give you the following list, with the string entries coming before the list entries:

[('a', '11'), ('g', 'a'), ('c', [1, 3, 4]), ('b', [1, 2, 3])]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.