检查所有值是否存在为词典中的键

Bat*_*man 5 python

我有一个值列表和一个字典.我想确保列表中的每个值都作为字典中的键存在.目前我正在使用两套来确定字典中是否存在任何值

unmapped = set(foo) - set(bar.keys())
Run Code Online (Sandbox Code Playgroud)

有没有更多的pythonic方式来测试这个?感觉有点像黑客?

use*_*203 3

您的方法将会起作用,但是,转换为set.

\n\n

具有相同时间复杂度的另一个解决方案是:

\n\n
all(i in bar for i in foo)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这两个都有时间复杂度O(len(foo))

\n\n
bar = {str(i): i for i in range(100000)}\nfoo = [str(i) for i in range(1, 10000, 2)]\n\n%timeit all(i in bar for i in foo)\n462 \xc2\xb5s \xc2\xb1 14.8 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\n\n%timeit set(foo) - set(bar)\n14.6 ms \xc2\xb1 174 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 100 loops each)\n\n# The overhead is all the difference here:\n\nfoo = set(foo)\nbar = set(bar)\n\n%timeit foo - bar\n213 \xc2\xb5s \xc2\xb1 1.48 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这里的开销有很大的不同,所以我会选择all这里。

\n