我试图找出如何将键和值对从一个过滤器过滤到另一个过滤器
例如,我想采取这个哈希
x = { "one" => "one", "two" => "two", "three" => "three"}
y = x.some_function
y == { "one" => "one", "two" => "two"}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
编辑:应该提一下,在这个例子中,我希望它表现为白名单过滤器.也就是说,我知道我想要什么,而不是我不想要的.
我有一个字典,并希望将其中的一部分传递给一个函数,该部分由一个列表(或元组)给出.像这样:
# the dictionary
d = {1:2, 3:4, 5:6, 7:8}
# the subset of keys I'm interested in
l = (1,5)
Run Code Online (Sandbox Code Playgroud)
现在,理想情况下我希望能够做到这一点:
>>> d[l]
{1:2, 5:6}
Run Code Online (Sandbox Code Playgroud)
...但这不起作用,因为它会寻找一个名为的钥匙(1,5).并且d[1,5]甚至不是有效的Python(虽然看起来它会很方便).
我知道我可以这样做:
>>> dict([(key, value) for key,value in d.iteritems() if key in l])
{1: 2, 5: 6}
Run Code Online (Sandbox Code Playgroud)
或这个:
>>> dict([(key, d[key]) for key in l])
Run Code Online (Sandbox Code Playgroud)
这更紧凑...但我觉得必须有一个"更好"的方式来做到这一点.我错过了更优雅的解决方案吗?
(我使用的是Python 2.7)
我有一系列的钥匙:
keys = ["first_name", "last_name", "foo"]
Run Code Online (Sandbox Code Playgroud)
和哈希:
hsh = {"first_name" => "tester", "zoo" => "loo", "foo" => "bar"}
Run Code Online (Sandbox Code Playgroud)
我想提取其键存在于数组中的键值对,以获得:
res = {"first_name" => "tester", "foo" => "bar"}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?