Python从元组列表中生成dicts列表

时间:2018-05-15 11:36:09

标签: python python-2.7 list dictionary tuples

从数据库我得到格式的结果:

result = ([('A', 210L), ('B', 1L), ('C', 269L)], 3)

我需要在Python中将其更改为:

[{'description':'A','sum':210},{'description':'B','sum':1},{'description':'C','sum':269}]

我尝试了各种选择,但没得到我需要的东西..

rows = len(result[0])
description_sum = {}
all_descriptions_sums = []
for i in range(rows):
    description_sum['description'] = result[0][i][0]
    description_sum['sum'] = int(result[0][i][1])
    all_descriptions_sums.append(description_sum)
return all_descriptions_sums

结果是:

[{'description':'C','sum':269},{'description':'C','sum':269},{'description':'C','sum':269}]

所以在步骤all_descriptions_sums.append(description_sum)中,字典不仅仅附加到列表中,而且还重写了以前的值..

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:6)

你可以使用列表理解:

result = [{'description': a, 'sum': int(b)} for a, b in result[0]]

但是如果你不想,你的代码中有什么问题,那就是你在循环之前初始化字典。您必须在每次迭代中重新声明它,如:

rows = len(result[0])
all_descriptions_sums = []
for i in range(rows):
    description_sum = {}
    description_sum['description'] = result[0][i][0]
    description_sum['sum'] = int(result[0][i][1])
    all_descriptions_sums.append(description_sum)
return all_descriptions_sums

答案 1 :(得分:2)

您需要将description_sum移动到for循环。

all_descriptions_sums = []
for i in range(rows):
    description_sum = {}
    description_sum['description'] = result[0][i][0]
    description_sum['sum'] = int(result[0][i][1])
    all_descriptions_sums.append(description_sum)

你可以使用列表理解来使其更清晰,如其他答案所示。

答案 2 :(得分:0)

以下代码将解决您的问题:

iconUrl: 'images/stop_black.png

一旦您对上述内容感到满意,我们可以将上述所有内容缩短为两行:

# Input data
result = ([('A', 210L), ('B', 1L), ('C', 269L)], 3)
# Result list
list_result = []
# The input is:
# - a 2-tuple containing:
#   - a list of 2-tuples with (database field) values
#   - length of the list ("number of rows returned")
# Therefore we iterate the first member of the outermost 2-tuple
for item in result[0]:
    # Long version for clarity:
    d = dict()
    d['description'] = item[0]
    d['sum'] = int(item[1])
    list_result.append(d)
    # The short version:
    # list_result.append({'description': item[0], 'sum': int(item[1])})