2

I am using pyodbc to query database and retrieve some data (obviously). What I would like is to create new dictionaries namd according to values returned from query. For example I have a table with 1000 items, and one of collumns in that table is a INT number which is in range 1-51. I want to do a rundown through my table, and create dictionaries named : bought_I, sold_I, created_I, etc... where I stands for INT number. I hope I am clear enough :) I know I could premade those dicts, but range will not always be 1-51, and it's nicer and cleaner to do it programmatically than to hardcode it.

ch1zra
  • 21
  • 1
  • 2
  • 2
    Why not use another layer of dicts, or, even better, a combination of dicts and lists? –  Jul 20 '11 at 12:00
  • possible duplicate of [Python - efficient way to create 20 variables?](http://stackoverflow.com/questions/6678547/python-efficient-way-to-create-20-variables) and see also http://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided – Fred Foo Jul 20 '11 at 12:03

1 Answers1

9

Don't.

Create a dictionary bought, and give it keys based on your number:

bought = {}
for number in column_x:
    bought[number] = "whatever object you need here"

Same for sold, created etc.

Or just one big dict:

mydict = {"bought": {}, "sold": {}, "created": {}}
for number in column_x:
    for key in mydict:
        mydict[key][number] = "whatever"
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561