请在以下情况下使用python 3.7帮助我获取代码: 我有一个元组列表作为输入,例如: 盒子= [(10,40,50,20),(15,40,50,20)] 我想创建一个词典列表,以便我的输出采用以下格式:
[
{
"top":10,
"right":40,
"bottom":50,
"left":20
},
{
"top":15,
"right":40,
"bottom":50,
"left":20
}
]
我尝试了json.dumps(),但未获得预期格式
答案 0 :(得分:3)
boxes = [(10,40,50,20),(15,40,50,20)]
dicts = []
for b in boxes:
top, right, bottom, left = b
dicts.append({'top': top, 'right': right, 'bottom': bottom, 'left': left})
print(dicts)
答案 1 :(得分:2)
这可以通过列表理解轻松完成。
在下面的函数中,将输入列表中的每个值元组与键列表一起压缩,以创建所需的键值对,这些键值对又用于初始化字典对象。
keys = ["top", "right", "bottom", "left"]
def convert(list_of_tuples):
return [dict(zip(keys, vals)) for vals in list_of_tuples]
答案 2 :(得分:1)
首先想到的是:
boxes = [(10,40,50,20),(15,40,50,20)]
new_boxes = []
for box in boxes:
new_boxes.append({'top': box[0],
'right': box[1],
'bottom': box[2],
'left': box[3]})
print(new_boxes)
答案 3 :(得分:0)
您必须遍历每个元组并使用该元组创建字典。
>>> t = [(10,40,50,20),(15,40,50,20)]
>>> d = []
>>> for i in t:
... d.append({'top': i[0], 'right': i[1], 'bottom': i[2], 'left': i[3]})
...
>>> d
[{'top': 10, 'right': 40, 'bottom': 50, 'left': 20}, {'top': 15, 'right': 40, 'bottom': 50, 'left': 20}]
答案 4 :(得分:0)
您可以遍历列表,可以按如下方式创建字典
final = []
for t in m_tuple_list:
final.append({ 'top': t[0], 'bottom': t[1], 'left': t[2], 'right': t[3] })
print (final)
答案 5 :(得分:0)
您可以使用map
对列表的元素应用相同的操作。
def convert(x):
return {
"top":x[0],
"right":x[1],
"bottom":x[2],
"left":x[3]
}
inputs = [(10,40,50,20),(15,40,50,20)]
list_dic = list(map(convert, inputs))
print(list_dic)
# output
#[{'top': 10, 'right': 40, 'bottom': 50, 'left': 20},
#{'top': 15, 'right': 40, 'bottom': 50, 'left': 20}]