开发者

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-st开发者_开发百科atement. 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????


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜