Reputation: 6246
I have a .fetchall() result like this:
t = (('oranges',), ('apples',), ('pears',))
How do I turn this into a dictionary like this:
d = {'oranges':None, 'apples':None, 'pears':None}
Upvotes: 0
Views: 442
Reputation: 879113
In Python2.7 or better, the fastest way is to use a dict comprehension:
In [12]: {item[0]: None for item in t}
Out[12]: {'apples': None, 'oranges': None, 'pears': None}
For older versions of Python, there is the fromkeys method:
In [6]: dict.fromkeys([row[0] for row in t])
Out[6]: {'apples': None, 'oranges': None, 'pears': None}
So how to decide which one to use? If all methods are equally readable, I go with whichever one is fastest:
In [17]: t = [(str(i),) for i in range(10000)]
In [18]: %timeit dict((item[0], None) for item in t)
100 loops, best of 3: 3.36 ms per loop
In [19]: %timeit dict.fromkeys([row[0] for row in t])
100 loops, best of 3: 2.54 ms per loop
In [20]: %timeit {item[0]: None for item in t}
100 loops, best of 3: 2.24 ms per loop
Upvotes: 1
Reputation: 4976
>>> t = (('oranges',), ('apples',), ('pears',)
>>> dict((item[0], None) for item in t)
{'pears': None, 'apples': None, 'oranges': None}
Upvotes: 2