我有这本字典:
dic = {
'foo': ['one', 'two', 'three'],
'bar': ['four', 'five', 'six'],
'baz': ['seven', 'eight', 'nine']
}
从这个列表中:
my_list = ['one', 'five', 'nine']
我想在字典中搜索相应的键以获得这个新列表:
['foo', 'bar', 'baz']
我的实际工作代码是:
l = []
for el in my_list:
for d_key, d_val in dic.items():
if el in d_val:
l.append(d_key)
print(l)
但我认为还有一种更像Python的方式。有什么想法吗?你知道吗
编辑:
多亏了TigerhawkT3的建议(可读性很重要,但实用性胜过纯粹性),为了直接得到值,我选择了反转字典。现在我的代码看起来像:
dic = {'one': 'foo', 'two': 'foo', 'three': 'foo', 'four': 'bar', 'five': 'bar', 'six': 'bar', 'seven': 'baz', 'nine': 'baz', 'eight': 'baz'}
my_list = ['one', 'five', 'nine']
print([dic[x] for x in my_list])
我先把字典翻过来:
然后可以应用替换:
编辑:如果需要保留关键字,当字典不包含匹配项时,可以将第二行替换为:
可以使用^{} 检查a键值是否与元组有公共元素。你知道吗
如果关键问题的顺序是:
相关问题 更多 >
编程相关推荐