简体   繁体   中英

How to convert array of tuple to dictionary

I'm new for psycopg2 and postgress, i can able to retrieve data from
postgress. but I'm facing following issue

      kart_user = "kart_user"
      token = 'acf98c76a70a4a67b6d503377279c7da'
      cond = "token"+ " = " +"'{}'".format(token)
      cur = conn.cursor()
      cur.execute("SELECT * FROM "+ kart_user +" where "+cond +" ;")
      res = cur.fetchall()
      data = cur.fetchall()
      print data

Output

[('acf98c76a70a4a67b6d503377279c7da', 'sssssssss', 'hello', 'sssssss')]

Output is array of tuple format ,i want to retrieve in the form of dictionary

eg:  data['token']

How can i solve this issue? thank you

DataDictionary ={} //out of the data collection loop

while collectingData==True:
    DataDictionary['%s'%token] = data[0][1:]

this will create a dictionary and add a entry with the token (in string form) as a key. If another variable is suitable as a unique key you could use that.

retrieve a specific key using one of the methods below

DataDictionary['acf98c76a70a4a67b6d503377279c7da'] = ('sssssssss', 'hello', 'sssssss')

or DataDictionary[token] = ('sssssssss', 'hello', 'sssssss')

If you want the data in the form of a dictionary you must first create the dictionary with the line:

DictionaryName={ }

This initialisation of the dictionary should be done outside of the data collection loop or you will lose the old data.

You could simplify the data addition line to:

DataDictionary['%s'%token] = data

But this keeps the data nested in unnecessary lists. If it needs to be simpler then perhaps i am not understanding what you really need from this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM