0

I want to basically have a sorted list of my list of dictionaries that looks like:

similarity = [{'Ben': 49}, {'Moose': 18}, {'Reuven': 39}, {'Cust1': 58}, {'Cust2': 10}, {'Francois': 58}, {'Jim C': 39}, {'Iren': 13}, {'Cust3': 13}]

Any help is appreciated, and thanks in advance.

2
  • 2
    Can I ask why you're using a list of single-entry dictionaries? Could these be merged into a single dictionary? Commented Apr 14, 2012 at 22:19
  • 1
    @senderle: Or maybe he could just use a list of tuples... Commented Apr 14, 2012 at 22:31

3 Answers 3

4

You should be using a list of tuples here:

>>> lst = [d.items()[0] for d in similarity]
>>> lst
[('Ben', 49), ('Moose', 18), ('Reuven', 39), ('Cust1', 58), ('Cust2', 10), ('Francois', 58), ('Jim C', 39), ('Iren', 13), ('Cust3', 13)]

Then you can sort those as usual.

>>> from operator import itemgetter
>>> sorted(lst, key=itemgetter(1))
[('Cust2', 10), ('Iren', 13), ('Cust3', 13), ('Moose', 18), ('Reuven', 39), ('Jim C', 39), ('Ben', 49), ('Cust1', 58), ('Francois', 58)]

If you want, you can also use a single, ordered dictionary to hold the values:

>>> from collections import OrderedDict
>>> OrderedDict(sorted(lst, key=itemgetter(1)))
OrderedDict([('Cust2', 10), ('Iren', 13), ('Cust3', 13), ('Moose', 18), ('Reuven', 39), ('Jim C', 39), ('Ben', 49), ('Cust1', 58), ('Francois', 58)])
Sign up to request clarification or add additional context in comments.

Comments

1

This is one way of doing it.

>>> sorted(similarity, key=lambda x: x.values()[0])
[{'Cust2': 10}, {'Iren': 13}, {'Cust3': 13}, {'Moose': 18}, {'Reuven': 39}, {'Jim C': 39}, {'Ben': 49}, {'Cust1': 58}, {'Francois': 58}]

Comments

0

I face difficulty in this.
So I suggest you do in this method

a = {'Ben': 49}
b =  {'Moose': 18}
ab = {**a, **b}
print(ab)
{'Ben': 49, 'Moose': 18}

1: sorted(ab.values())
[('Ben', 49), ('Moose', 18)]

2: sorted(ab.items())
[18, 49]

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.