如何基于第一个元素比较两个列表并将匹配的值放入字典中?

时间:2018-09-17 20:37:25

标签: python python-3.x list dictionary

list1 = [4356, 'abc']
list2 = {4356: ('5986', '5987'), 6598: ('6593', '2659')}

如何比较基于第一个元素(在这种情况下为'4356'元素)的两个列表,并在添加了'True'单词的字典中将list2中的匹配值获取到字典中?

我需要输出像这样:

output = {'5986':'True', '5987':'True'}

1 个答案:

答案 0 :(得分:1)

list1 = [4356, 'abc']
list2 = {4356: ('5986', '5987'), 6598: ('6593', '2659')}

output = {x: True for x in list2[list1[0]]}
print(output)  # {'5986': True, '5987': True}

或者,使用您评论中的list2

list1 = [4356, 'abc']
list2 = [(4356, '5986'), (4356, '5987'), (6598, '6593'), (6598, '2659')]

output = {val: True for key, val in list2 if key == list1[0]}
print(output)  # {'5986': True, '5987': True}