How to show a dictionary sorted on a value within its data?

Joel Goldstick joel.goldstick at gmail.com
Wed Oct 1 06:37:51 EDT 2014


On Wed, Oct 1, 2014 at 5:58 AM,  <cl at isbd.net> wrote:
> I have a dictionary as follows:-
>
> {
> u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', conv=6834.374834509803, Description=u'Starter Amps'),
> u'LeisureVolts': Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, Description=u'Leisure Volts'),
> u'RudderPos': Row(id=6, ain=u'AIN5', name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'),
> u'xx': Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''),
> u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', conv=32.727273081945, Description=u'Leisure Amps'),
> u'StarterVolts': Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, Description=u'Starter Volts')
> }

Is Row a function?  Or do you have a key with a tuple as the value?
>
> I want to output a menu to a user comprising some parts of the
> dictionary (ain and Description) sorted by ain.
>
> Is there some incantation of sorted() that will do what I want?  I
> can't quite fathom out the 'key=' parameter needed to sort it by the
> tuple item.  Maybe I need a cmp= ?
>
> E.g. I want to do something like:-
>
>     for meas in sorted(adc.cfg, key=???):
>         print(adc.cfg[meas].ain, adc.cfg[meas].Description)
>
> What's needed in the ???
>
> --
> Chris Green
> ·

You might read here:
http://www.pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com



More information about the Python-list mailing list