What's the neatest way of getting dictionary entries in a specified order?

gvmcmt at gmail.com gvmcmt at gmail.com
Wed Mar 8 15:42:45 EST 2017


On Thursday, March 9, 2017 at 1:03:31 AM UTC+5:30, Chris Green wrote:
> I have a fairly simple application that populates a GUI window with
> fields from a database table.  The fields are defined/configured by a
> dictionary as follows:-
> 
>     # 
>     # 
>     # Address Book field details, dictionary key is the database column 
>     # 
>     dbcol = {}
>     dbcol['firstname'] = col('First Name', True, False)
>     dbcol['lastname'] = col('Last Name', True, False)
>     dbcol['email'] = col('E-Mail', True, True)
>     dbcol['phone'] = col('Phone', True, True)
>     dbcol['mobile'] = col('Mobile', True, True)
>     dbcol['address'] = col('Address', True, False)
>     dbcol['town'] = col('Town/City', True, False)
>     dbcol['county'] = col('County/Region', True, False)
>     dbcol['postcode'] = col('PostCode', True, False)
>     dbcol['country'] = col('Country', True, False)
>     dbcol['notes'] = col('Notes', True, False)
>     dbcol['www'] = col('Web Page', True, True)
>     dbcol['categories'] = col('Categories', True, True)
> 
> How can I get the fields in the GUI window in the order I want rather
> than the fairly random order that they appear in at the moment?
> 
> Currently the GUI fields are populated by a for loop as follows:-
> 
>     # 
>     # 
>     # Put values into the fields 
>     # 
>     i = 0
>     for col, field in abookdb.dbcol.items():
>         print(field.heading)
>         if (i > numkeys/2):
>             self.addfieldentry(col, address, field, self.rtable, i-numkeys/2)
>         else:
>             self.addfieldentry(col, address, field, self.ltable, i)
>         i = i + 1
> 
> The for loop gets the items from the dictionary in an order that isn't
> what I want.  How can I configure things so they're in the order I want?
> 
> -- 
> Chris Green
> ·

There is OrderedDict.

https://docs.python.org/2/library/collections.html#collections.OrderedDict

https://docs.python.org/3/library/collections.html#collections.OrderedDict


More information about the Python-list mailing list