切片字典 [英] Slicing a dictionary

查看:84
本文介绍了切片字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,并希望将其一部分传递给函数,该部分由键列表(或元组)给出.像这样:

I have a dictionary, and would like to pass a part of it to a function, that part being given by a list (or tuple) of keys. Like so:

# the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)

现在,理想情况下,我希望能够做到这一点:

Now, ideally I'd like to be able to do this:

>>> d[l]
{1:2, 5:6}

...,但这不起作用,因为它将查找名为(1,5)的键. 而且d[1,5]甚至不是有效的Python(尽管似乎很方便).

... but that's not working, since it will look for a key named (1,5). And d[1,5] isn't even valid Python (though it seems it would be handy).

我知道我可以做到:

>>> dict([(key, value) for key,value in d.iteritems() if key in l])
{1: 2, 5: 6}

或者这个:

>>> dict([(key, d[key]) for key in l])

更紧凑 ...但是我觉得必须有一种更好"的方式来做到这一点.我想念一个更优雅的解决方案吗?

which is more compact ... but I feel there must be a "better" way of doing this. Am I missing a more elegant solution?

(我正在使用Python 2.7)

(I'm using Python 2.7)

推荐答案

您应该遍历元组并检查键是否在dict中,而不是相反,如果您不检查键是否存在以及它不会在字典中,您将得到一个关键错误:

You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:

print({k:d[k] for k in l if k in d})

一些时间:

 {k:d[k] for k in set(d).intersection(l)}

In [22]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in l}
   ....: 
100 loops, best of 3: 11.5 ms per loop

In [23]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
   ....: 
10 loops, best of 3: 20.4 ms per loop

In [24]: %%timeit                        
l = xrange(100000)
l = set(l)                              
{key: d[key] for key in d.viewkeys() & l}
   ....: 
10 loops, best of 3: 24.7 ms per

In [25]: %%timeit                        

l = xrange(100000)
{k:d[k] for k in l if k in d}
   ....: 
100 loops, best of 3: 17.9 ms per loop

我看不到{k:d[k] for k in l}的可读性或优雅性,如果所有元素都在d中,那么它会非常有效.

I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.

这篇关于切片字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆