在字典中查找首先出现在列表中的键

时间:2015-07-19 03:44:21

标签: python-2.7

我有一个列表和字典如下:

List1 = ['a', 'b', 'c', 'd']
d1 = OrderedDict([('c', '1'), ('b', '2')])

假设List1是一个排序列表。如何找到d1中首先出现的List1中的密钥?在其'b'

之上的示例中

我的代码低于 -

print d1.items()
d2={}
for key in d1:
   d2 [key]=List1.index(key)
print "Output is", min(d2.items(), key=lambda x: x[1])[0]

代码很冗长。我希望更高效的代码,可能是一行代码。

编辑:字典的所有键都出现在列表中。

2 个答案:

答案 0 :(得分:1)

平均而言,x in setO(1)x in listO(n)

In [17]: List1 = ['a', 'b', 'c', 'd']

In [18]: d1 = OrderedDict([('c', '1'), ('b', '2')])

In [19]: for key in List1:
   ....:     if key in d1:
   ....:         print key
   ....:         break
   ....:
b

答案 1 :(得分:1)

如果您只想拥有前置优先权,那么Sait发布的代码就是这样做的。如果您希望获得列表中序列中找到的所有键,则可以在列表中找到以下帮助。此外,返回列表的第一个元素当然是第一个找到的元素。

from collections import OrderedDict

List1 = ['a', 'b', 'c', 'd']
d1 = OrderedDict([('c', '1'), ('b', '2')])

found  = [el for el in List1 if el in d1]