aleho
aleho

Reputation: 109

add item to dictionary

i read a lot in that forum, but i couldn't find a proper way to add all items to my dictionary... So maybe someone can help me! first a explanation:

rows = cur.fetchall() 
columns=[desc[0] for desc in cur.description]  
GID_Distances = {}  
if len(rows) > 0:
    for row in rows:
      items = zip(columns, row)
      GID_Distances = {}
      for (name,  value) in items:
         GID_Distances[name]=value

rows is a list from a sql-statement. so in that list are several values with the same key... I just want to get something like a table something like this: {['id': 1, 'point':2], ['id':2, 'point':3]} but for the loop above is the result just the last item, because it overwrites all before. Any ideas????

Upvotes: -1

Views: 2914

Answers (2)

kennytm
kennytm

Reputation: 523284

If you have an iterable of pairs i.e. [(k1,v1),(k2,v2),...], you could apply dict on it to make it a dictionary. Therefore, your code could be written simply as

rows = cur.fetchall() 
columns = [desc[0] for desc in cur.description]  
# or: columns = list(map(operator.itemgetter(0), cur.description))
#     don't call list() in Python 2.x.
GID_Distances = [dict(zip(columns, row)) for row in rows]
# note: use itertools.izip in Python 2.x

Upvotes: 3

aaronasterling
aaronasterling

Reputation: 71004

you are redefining GID_Distances to a blank dictionary in the loop without first storing the value. store the rows in a list like so:

rows = cur.fetchall() 
columns=[desc[0] for desc in cur.description]  
results = []
for row in rows:
  GID_Distances = {} 
  items = zip(columns, row)
  for (name,  value) in items:
     GID_Distances[name]=value
  results.append(GID_Distances)

Upvotes: 2

Related Questions