469,608 Members | 2,152 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,608 developers. It's quick & easy.

Nested Dictionary Sorting

Hi,

I am fairly new to the python language and am trying to sort a nested
Dictionary of a Dictionary which I wish to sort by value. The dictionary
does not have to be restructured as I only need it sorted in this way
for printing purposes.

The following is an example of my Dictionary printed with 'print
dictionary.items()', where '2329513' is the key of the first hash, 'ops'
is the key of the second hash and '50.0' is the value of the second hash
which I would like to sort by:
[('2329513', {'ops': 20.0}), ('2329492', {'ops': '80'}), ('2329490',
{'ops': '50'})]

I hope to sort these first keys by the value of the 'ops' key from
highest to lowest value to give the following result:
[('2329492', {'ops': '80'}), ('2329490', {'ops': '50'}), ('2329513',
{'ops': 20.0})]

Thanks in advance for any help,
Sam.


Nov 7 '06 #1
1 3045
Sam Loxton wrote:
I am fairly new to the python language and am trying to sort a nested
Dictionary of a Dictionary which I wish to sort by value. The dictionary
does not have to be restructured as I only need it sorted in this way
for printing purposes.

The following is an example of my Dictionary printed with 'print
dictionary.items()', where '2329513' is the key of the first hash, 'ops'
is the key of the second hash and '50.0' is the value of the second hash
which I would like to sort by:
[('2329513', {'ops': 20.0}), ('2329492', {'ops': '80'}), ('2329490',
{'ops': '50'})]

I hope to sort these first keys by the value of the 'ops' key from
highest to lowest value to give the following result:
[('2329492', {'ops': '80'}), ('2329490', {'ops': '50'}), ('2329513',
{'ops': 20.0})]
If Dennis' remarks don't apply because you simplified your problem for the
post:
>>d = {'2329513': {'ops': 20.0}, '2329492': {'ops': '80'}, '2329490':
{'ops': '50'}}
>>items = d.items()
def key(item):
.... return item[1]["ops"]
....
>>items.sort(key=key, reverse=True)
items
[('2329492', {'ops': '80'}), ('2329490', {'ops': '50'}), ('2329513', {'ops':
20.0})]

Peter
Nov 7 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by B0nj | last post: by
2 posts views Thread by techiepundit | last post: by
3 posts views Thread by Jake Emerson | last post: by
12 posts views Thread by Rich Shepard | last post: by
1 post views Thread by hermesbaby | last post: by
2 posts views Thread by =?Utf-8?B?RGF2aWQgTW9ycmlz?= | last post: by
reply views Thread by guiromero | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.