0

I haven't been able to figure out how to return the values as a dictionary, for example, if dic = true it would return {’idx’: 3, ’name’: ’me’, ’passwd’ ’a9993e364706816aba3e25717850c26c9cd0d89d’}

def retrieve(self, idx, dic = True):
    '''
    returns a tuple with the three
    values of the record with index idx, or returns None
    if an exception occurred, if the
    option dict is False. By default,
    dict=True and on return is a dictionary with the
    keys ’idx’, ’name’ and ’passwd’.
    The values in the dictionary correspond to the fields
    in the record with index idx
    '''


    if dic == False:

        query = 'SELECT * FROM players WHERE idx = ?'

        self.cr.execute(query)

    if dic == True:

        query = 'SELECT * FROM players WHERE idx = ?'

        self.cr.execute(query)

    self.db.commit()

    print(self.cr.fetchall())

I tried running the function with the idx as a string input and it was able to fetch me the tuple without the dictionary, but I believe this is more of a formatting issue. Any help would be appreciated.

3
  • you docstrings are lying, parameter was renamed into dic Apr 11, 2017 at 23:23
  • instead of if some_flag == True/if some_flag == False just do if some_flag/if not some_flag Apr 11, 2017 at 23:34
  • also docstrings supposed to be in triple double quotes Apr 11, 2017 at 23:41

1 Answer 1

2

if you want to make dictionary from tuple, you can store your columns names in some variable and then build dictionary from columns names and your records tuples with zip like

def retrieve(self, idx, dic=True):
    query = 'SELECT * FROM players WHERE idx = {idx}'.format(idx=idx)
    self.cr.execute(query)
    self.db.commit()

    records_tuples = self.cr.fetchall()
    if dic:
        columns_names = ['idx', 'name', 'passwd']
        records_dicts = [dict(zip(columns_names, record_tuple))
                         for record_tuple in records_tuples]
        return records_dicts
    else:
        return records_tuples
1
  • thank you very much, this was exactly what I was looking for!
    – Frozease
    Apr 12, 2017 at 3:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.