[Tutor] Tutor Digest, Vol 54, Issue 16
Lie Ryan
lie.1296 at gmail.com
Wed Aug 6 12:22:22 CEST 2008
> Message: 1
> Date: Tue, 5 Aug 2008 11:08:57 -0400
> From: "Bryan Fodness" <bryan.fodness at gmail.com>
> Subject: [Tutor] iterating data and populating a dictionary
> To: "tutorpythonmailinglist Python" <tutor at python.org>
> Message-ID:
> <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> i am filling a dictionary with a dictionary and my values for
> isegment[field] are identical. i can't see where i am overwriting the
> previous field values.
>
> my data looks like
>
> Field = aa1
> Index = 0.0
> Value = 0.0
> ...
> ...
> Field = aa2
> Index = 0.01
> Value = 0.5
> ...
>
>
> i would like to have something like, {1: {'Value': 0.0, ...}, 2:
> {'Value':0.01, ...}}
Why don't you use a list of dictionaries instead of dictionaries of
dictionaries?
>
> for line in file(data_file):
> the_line = line.split()
It's better to use: line.split('=', 1)
then you should consider stripping its values, especially the one to be
used as the key to the dictionary.
> if the_line:
> if the_line[0] == 'Field':
> field += 1
if this code snippet is the only code in your program, field would cause
NameError. However, I assume you have declared field somewhere outside
this line, and field is a local variable. If that is the case, remember
that local variable is deleted when it is out of scope. This might be
the reason why Fields got overwritten.
> elif the_line[0] == 'Index':
> index = float(the_line[-1])
If you use .split('=', 1), you can be sure that the value of the
dictionary is on the_line[1] and the key of the dictionary is on
the_line[0] (assuming = is not a legal character for key name)
> dif_index = index - start_index
> iindex[field] = dif_index
> start_index = index
> elif the_line[0] == 'Value':
> segment[the_line[1]] = float(the_line[-1])*(ax/40)
> isegment[field] = segment
This particular snippet isn't enough to localize the source of your
problem.
More information about the Tutor
mailing list