Pythonic查找和替换列表字典的方法

时间:2016-07-12 07:55:59

标签: python dictionary

我有这本词典:

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)

但我认为有更多的Pythonic方式。有什么想法吗?

修改

感谢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])

2 个答案:

答案 0 :(得分:3)

我会先翻译字典:

invdic = {val: key for key in dic for val in dic[key]}

然后你可以申请替换:

l = ['one', 'five', 'nine']
l = list(invdic[x] for x in l)
print(l)

编辑:如果您需要保留关键字,当字典不包含匹配项时,您可以将第二行替换为:

l = list(invdic.get(x, x) for x in l)

答案 1 :(得分:2)

您可以使用isdisjoint()检查键值是否与元组有共同元素。

>>> s = set(my_list)
>>> [key for key, value in dic.items() if not s.isdisjoint(value)]
['foo', 'baz', 'bar']

如果关键的顺序是:

>>> [key for item in my_list for key, value in dic.items() if item in value]
['foo', 'bar', 'baz']