无法遍历列表以创建密钥对
Unable to iterate through list for creating Key pair
我正在尝试使用密钥对迭代和映射列表。我得到如下输出(即)我只得到列表中的最后一个值。
{'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'}]}
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
您可以使用 dict 和 zip 组合,如下所示:
dict(zip(samplelist, tags))
注意:您可能没有意识到这一点,但您缺少一个引号。标签应该是这样的:
tags = [[{'Key': 'Created', 'Value': '2019'}, {'Key': 'Type', 'Value': 'Business'}], [{'Key': 'Created', 'Value': '2020'}, {'Key': 'Type', 'Value': 'Entr'}]]
我正在尝试使用密钥对迭代和映射列表。我得到如下输出(即)我只得到列表中的最后一个值。
{'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'}]}
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
您可以使用 dict 和 zip 组合,如下所示:
dict(zip(samplelist, tags))
注意:您可能没有意识到这一点,但您缺少一个引号。标签应该是这样的:
tags = [[{'Key': 'Created', 'Value': '2019'}, {'Key': 'Type', 'Value': 'Business'}], [{'Key': 'Created', 'Value': '2020'}, {'Key': 'Type', 'Value': 'Entr'}]]