1

I need to create a set of dictionaries from Oracle query results.

My data is laid out into station ID, date, time, location, species, and catch weight. For each species, there is a new line, while all the location, etc, data may be redundant.

First, I need to create a keyed dictionary by fieldname and value, such as stationID, date, etc so that when I call, say,

value[1]  (this being the station ID field)

I get

112

The end result is to conglomerate all of the "like" station ID's, dates, etc into one unique key-- with the resulting data (fish catch) being the values.

such as [date,time,location, etc]: cod 47, hake 31, dogfish 5

So far, to get the data parsed into individual keyed dictionaries by field name and then by line I have this:

desc=[d[0] for d in cursor.description]
field=[d[1] for d in cursor.description]
value=dict(zip(desc,field))   
result=[dict(zip(value,line)) for line in cursor]
print result[1]

However, if I try and call value, the field is simply the data type.. how can I get the actual data value? And then nest that into the "result" dictionary that parses each individual sample?

6
  • I think you want result[0]['station ID'] instead, where result is a list of dictionaries, one per result row, judging by your code attempt. Commented Dec 17, 2012 at 15:38
  • I see what you're saying...if I try this, however, I get a key error, though the inputted key is identical to what I used in the query... Commented Dec 17, 2012 at 15:43
  • Brilliant..thank you. I knew I was over thinking it... Commented Dec 17, 2012 at 15:50
  • Actually, how can I print all the stations? result[???]['STATION']... I'm assuming it needs to be some "for" loop command? Commented Dec 17, 2012 at 15:58
  • Yes, or a list comprehension: [r['STATION'] for r in result]. Commented Dec 17, 2012 at 16:05

1 Answer 1

3

You are zipping together the wrong items. Zip only desc and line, you do not need to use the second item in the cursor.description tuples:

desc=[d[0] for d in cursor.description]
result=[dict(zip(desc, line)) for line in cursor]
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, that's what I thought. That splits everything by sample... how can I then make each value callable? A split?
If you want to aggregate data, why not have Oracle do that for you? You can query with a GROUP BY and have a SUM() column.
Oh! I don't know why I didn't think of this. Can the results be read into a dictionary in the same manner?
Of course, all you are doing is processing standard cursor data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.