1

This is more of a best practice question. What I have created is working perfectly, but I am curious if there is a shorter method for creating a dictionary out of my current data structure.

I am reading tables out of a SQLite database, the data is returned as a list of tuples. eg

[(49, u'mRec49', u'mLabel49', 1053, 1405406806822606L, u'1405406906822606'), 
(48, u'mRec48', u'mLabel48', 1330, 1405405806822606L, u'1405405906822606'), 
(47, u'mRec47', u'mLabel47', 1220, 1405404806822606L, u'1405404906822606')...
] 

I want to take each column of the list-tuple structure, make it into a list, get the column name from the database and use that as the key holding the list. Later I turn my dictionary into JSON.

Here is my function I scratched up, it does the job, I just can't help wondering if there is a better way to do this.

def make_dict(columns, list_o_tuples):
    anary = {}
    for j, column in enumerate(columns):
        place = []
        for row in list_o_tuples:
            place.append(row[j])
        anary[column] = place
    return anary

make_dict(mDBTable.columns, mDBTable.get_table())

Note:the function shouldn't care about the table its presented, or the number or rows & columns in table.

drewski
  • 111
  • 2
  • 10
  • 3
    How can an SQLite table have arbitrary number of columns? – thefourtheye Jul 16 '14 at 13:13
  • Or [this](http://stackoverflow.com/q/6522446/189134) or [this](http://stackoverflow.com/questions/6586310/python-convert-list-of-key-value-tuples-into-dictionary) – Andy Jul 16 '14 at 13:14
  • Data structures are different, as well as my goals for structuring the dictionary. Read the question. – drewski Jul 16 '14 at 13:16
  • I have several different tables, each have different number of columns and rows. The function shouldn't care, what table it is presented with. – drewski Jul 16 '14 at 13:17
  • How about [Python Help: Creating a dict of {str:list of str} from csv file](http://stackoverflow.com/q/20292600) then? Or [How to use column names when creating JSON object, Python](http://stackoverflow.com/q/12270679). Both are closely related. – Martijn Pieters Jul 16 '14 at 13:21

2 Answers2

6

It seems that you want to transpose the list_o_tuples:

transpose = zip(*list_o_tuples)

And then zip that up with the column names:

return dict(zip(columns, transpose))
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

You can simply unzip the list_o_tuples and then using a dictionary comprehension create a new dictionary with the corresponding column data and the column header

columns = ["num1", "str1", "num2", "num3", "str2", "str3"]
print {columns[idx]:row for idx, row in enumerate(zip(*list_o_tuples))}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497