By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,645 Members | 1,047 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,645 IT Pros & Developers. It's quick & easy.

Nested Dictionary Sorting

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.