我有一个值列表1:
['A','B','C','D']
我有一个字典
{1: ['A','F'],2:['B','J'],3:['C','N'],4:['D','X']}
我想获取列表中每个值的键:
我尝试过:
[dict1[x] for x in list]
但是由于我没有考虑dict值是一个列表而不是单个值的事实而导致错误。我该如何实现?
我想要的输出将是带有list1值键的列表:
[1,2,3,4]
答案 0 :(得分:5)
您可以使用列表理解:
[k for x in lst for k, v in d.items() if x in v]
示例:
lst = ['A','B','C','D']
d = {1: ['A','F'],2:['B','J'],3:['C','N'],4:['D','X']}
print([k for x in lst for k, v in d.items() if x in v])
# [1, 2, 3, 4]
答案 1 :(得分:4)
您可以展平字典并将其用作查找:
data = ['A','B','C','D']
d = {1: ['A','F'],2:['B','J'],3:['C','N'],4:['D','X']}
new_d = {i:a for a, b in d.items() for i in b}
result = [new_d[i] for i in data]
输出:
[1, 2, 3, 4]