Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #85639

Re: Dictionary from sqlite3.Row and PyCharm unresolved reference

From Peter Otten <__peter__@web.de>
Subject Re: Dictionary from sqlite3.Row and PyCharm unresolved reference
Date 2015-02-13 12:33 +0100
Organization None
References <1a194e0a113d8d215970f15d910@nntp.aioe.org>
Newsgroups comp.lang.python
Message-ID <mailman.18727.1423827222.18130.python-list@python.org> (permalink)

Show all headers | View raw


Mario Figueiredo wrote:

> Currently i'm using the following code to transform a row fetched from an
> sqlite database into a dictionary property:

class Unknown:

>     def __init__(self, id_):
>         self.id = id_
>         self.data = None
>         ...
>         conn = sqlite3.connect('data')
>         conn.row_factory = sqlite3.Row
>         row = conn.execute(query, {'id': str(id_)}).fetchone()
>         conn.close()
> 
>         if row:
>             self.data = dict(zip(row.keys(), tuple(row)))
> 
> I have two questions:
> 
>   1. Is this an acceptable idiom for the construction of self.data
>   dictionary,
>       or do I have a better and more readable option?

If sqlite3.Row is not dict-like enough to use it directly

self.data = row

you can either convert the Row object with

self.data = dict(row)

or use the recipe for a row factory provided in the documentation at 

https://docs.python.org/dev/library/sqlite3.html#sqlite3.Connection.row_factory

that constructs a dict directly.

And now an unsolicited remark: if you have more than one instance of Unknown 
you might read the data outside the initialiser or at least keep the 
connection open and pass a connection or cursor object to the initialiser.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Dictionary from sqlite3.Row and PyCharm unresolved reference Mario Figueiredo <marfig@gmail.com> - 2015-02-13 10:26 +0000
  Re: Dictionary from sqlite3.Row and PyCharm unresolved reference Peter Otten <__peter__@web.de> - 2015-02-13 12:33 +0100
    Re: Dictionary from sqlite3.Row and PyCharm unresolved reference Mario Figueiredo <marfig@gmail.com> - 2015-02-13 19:46 +0100

csiph-web