我想从三个二维列表中创建一个字典。例如:
list1 = [['Brand', 'Release Date', 'Related'], ['Structure', 'Screen', 'Photos', 'Videos']]
list2 = [['Brand', 'Aliases'], ['Release date', 'State'], ['Predecessor', 'Successors'], ['Size', 'Aspect Ratio', 'Weight', 'Usable surface', 'Materials', 'Colors', 'Origami']]
list3 = [['OppoSmartphones by Oppo', 'PAFM00, Oppo Find X Standard Edition'], ['June 2018, 10 months ago', 'On Sale'], ['Oppo Find 7', 'Oppo Reno'], ['74.2 mm x 156.7 mm x 9.4 mm', '19:9', '186 g', '87 %', 'Glass', 'Turquoise Violet', 'Print 3D Model']]
我希望结果为
{'Brand':{'Brand': 'OppoSmartphones by Oppo', 'Aliases': 'PAFM00, Oppo Find X Standard Edition'}, 'Release Date':{ 'Release date': 'June 2018, 10 months ago', 'State': 'On Sale'}, 'Related':{'Predecessor': 'Oppo Find 7', 'Successors': 'Oppo Reno'}}
答案 0 :(得分:0)
尝试:
res = {}
for i in range(3):
res[list1[0][i]] = {list2[i][0]:list3[i][0], list2[i][1]:list3[i][1]}
答案 1 :(得分:0)
那么您可以使用循环dict()
和zip()
来实现这一点,如下所示:
list1 = [['Brand', 'Release Date', 'Related'],
['Structure', 'Screen', 'Photos', 'Videos']]
list2 = [['Brand', 'Aliases'], ['Release date', 'State'],
['Predecessor', 'Successors'],
['Size', 'Aspect Ratio', 'Weight', 'Usable surface', 'Materials', 'Colors', 'Origami']]
list3 = [['OppoSmartphones by Oppo', 'PAFM00, Oppo Find X Standard Edition'],
['June 2018, 10 months ago', 'On Sale'],
['Oppo Find 7', 'Oppo Reno'],
['74.2 mm x 156.7 mm x 9.4 mm', '19:9', '186 g', '87 %', 'Glass', 'Turquoise Violet', 'Print 3D Model']]
d1 = {}
for i in range(len(list1)):
for j in range(len(list1[i])):
#print(i,j)
d1[list1[i][j]] = dict(zip(list2[j], list3[j]))
# to get this patter: dict = {list1[0][0]:{list2[0][0]:list3[0][0], list2[0][1]:list3[0][1]},
# list1[0][1]:{list2[1][0]:list3[1][0], list2[1][1]:list3[1][1]},
# list1[0][2]:{list2[2][0]:list3[2][0], list2[2][1]:list3[2][1]}}
d2 = {}
for i in range(len(list1[0])):
if list1[0][i] not in d2.keys(): d2[list1[0][i]] = {}
if list1[0][i] not in d2.keys(): d2[list1[0][i]] = {}
d2[list1[0][i]][list2[i][0]] = list3[i][0]
d2[list1[0][i]][list2[i][1]] = list3[i][1]
# if you want to apply the behaviour on all elements:
d3 = {}
for k in range(len(list1)):
for i in range(len(list1[k])):
if list1[k][i] not in d3.keys(): d3[list1[k][i]] = {}
if list1[k][i] not in d3.keys(): d3[list1[k][i]] = {}
d3[list1[k][i]][list2[i][0]] = list3[i][0]
d3[list1[k][i]][list2[i][1]] = list3[i][1]
输出(d2):
{ 'Brand': {'Aliases': 'PAFM00, Oppo Find X Standard Edition',
'Brand': 'OppoSmartphones by Oppo'},
'Related': {'Predecessor': 'Oppo Find 7',
'Successors': 'Oppo Reno'},
'Release Date': {'Release date': 'June 2018, 10 months ago',
'State': 'On Sale'}}