ConfigParser.items sorting

Jon Clements joncle at googlemail.com
Wed Oct 28 02:50:30 EDT 2009


On 28 Oct, 06:21, Dean McClure <bratpri... at gmail.com> wrote:
> Hi,
>
> Just wondering how I can get the items() command from ConfigParser to
> not resort all the item pairs that it presents.
>
> I am trying to get it to read some data in order:
>
> [Relay Info]
> relay_name: IPC
> relay_current_range: [60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 100,
> 104, 108, 112, 116]
> relay_current_mutliplier: [1/8, 1/4, 1/2, 1, 2, 4]
> relay_i: arcfc/(relay_current_range*relay_current_mutliplier)
>
> so I can input the data and then eval() the equation at the end but
> when I go
> config.items('Relay Info')
> It mixes everything up, is there a way to stop this?
>
> Here is my selection code
>
> variables = sorted(config.items('Relay Info'))
> #Get inputs from user for each variable
> for variable in variables:
>         if variable[0] == 'relay_name':
>                 vars()[variable[0]] = variable[1]
>         else:
>                 vars()[variable[0]] = 'not a real thing this is just a fake that
> will never turn up to establish the variable'
>                 if variable[1][0] == '[' and variable[1][-1] == ']':
>                         if variable[0] != 'Any':
>                                 while (variable[1].count(vars()[variable[0]]) < 1):
>                                         vars()[variable[0]] = raw_input(str(variable)[1:-1] + "\n")
>                                         if variable[1].count(vars()[variable[0]]) < 1:
>                                                 print 'Setting unavailable'
>                         else:
>                                 vars()[variable[0]] = raw_input(str(variable)[1:-1] + "\n")
>                 else:
>                         vars()[variable[0]] = variable[1]
>                 vars()[variable[0]] = float(eval(vars()[variable[0]]))
>
> Thanks for the help!

I'm not 100% sure what you're asking, as why should the order be
important?

It's probably worth mentioning that the builtin dictionary type is
'unordered' as it uses hashing to store keys. However, the
ConfigParser module does allow you to supply a dict_type parameter in
version 2.6+ [http://docs.python.org/library/configparser.html], so
you could provide an 'ordered dictionary' which returns its items in
insertion order. There's lots of recipes out there for those, but I
believe Raymond Hettinger has a fairly good one on the ActiveState(?)
cookbook site. (Google for python cookbook).

Since however, the idea of processing INI files is that you *know*
what you're looking for and how to interpret it, I'm not sure why
you're not using something similar to this (v2.6.2):

relay_name = config.get('Relay Info', 'relay_name')
relay_current_range = config.get('Relay Info', 'relay_current_range')
relay_current_range_list = eval(relay_current_range)

...etc...

hth,

Jon.



More information about the Python-list mailing list