无法迭代列表以创建密钥对

问题描述 投票:-2回答:2

我正在尝试使用密钥对来迭代和映射列表。我正在获得以下输出(即)我只获得列表中的最后一个值。

{'first': [{'Key': 'Created', 'Value': '2020'}, {'Key': 'Type', 'Value': 'Entr'}], 'Second': [{'Key': 'Created', 'Value': '2020'}, {'Key': 'Type', 'Value': 'Entr'}]}

代码

tags = [[{'Key': 'Created', 'Value': '2019'}, {'Key': 'Type', 'Value': 'Business'}], [{'Key': 'Created', 'Value': '2020'}, {'Key': 'Type', 'Value': 'Entr'}]]

samplelist = ['first','Second']

sampledict = {}

for i in samplelist:
    for tag in tags:
        sampledict[i] = tag

预期输出

{'first': [{'Key': 'Created', 'Value': '2019'}, {'Key': 'Type', 'Value': 'Business'}], 'Second': [{'Key': 'Created', 'Value': '2020'}, {'Key': 'Type', 'Value': 'Entr'}]}
python dictionary key-value
2个回答
0
投票

您可以按以下方式使用dict和zip组合:

dict(zip(samplelist, tags))

注意:您可能没有意识到,但是缺少一个引号。标签应该是这样的:

tags = [[{'Key': 'Created', 'Value': '2019'}, {'Key': 'Type', 'Value': 'Business'}], [{'Key': 'Created', 'Value': '2020'}, {'Key': 'Type', 'Value': 'Entr'}]]

-1
投票
tags = [[{'Key': 'Created', 'Value': '2019'},
         {'Key': 'Type', 'Value': 'Business'}],
        [{'Key': 'Created', 'Value': '2020'},
         {'Key': 'Type', 'Value': 'Entr'}]]

samplelist = ['first', 'Second']
sampledict = {}
i=0
while i < len(samplelist):
    sampledict[samplelist[i]] = tags[i]
    i += 1
© www.soinside.com 2019 - 2024. All rights reserved.