从字典中提取键值对的子集?
我有一个大字典对象,有几个键值对(大约 16 个),但我只对其中 3 个感兴趣。对此类字典进行子集化的最佳方法(最短/有效/最优雅)是什么?
我所知道的最清楚的是:
bigdict = {'a':1,'b':2,....,'z':26}
subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']}
我确信有比这更优雅的方式。
I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to subset such dictionary?
The best I know is:
bigdict = {'a':1,'b':2,....,'z':26}
subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']}
I am sure there is a more elegant way than this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
你可以尝试:
...或者在 Python 2.7 或更高版本中:
我假设你知道键将在字典中。请参阅 如果您不这样做,请由 Håvard S 回答。
或者,正如 timbo 在评论中指出的那样,如果您想要
bigdict
中缺少的密钥要映射到None
,您可以这样做:如果您使用的是 Python 3,并且您只想要新字典中实际存在于原始字典中的键,您可以使用事实来查看对象实现一些集合操作:
You could try:
... or in Python versions 2.7 or later:
I'm assuming that you know the keys are going to be in the dictionary. See the answer by Håvard S if you don't.
Alternatively, as timbo points out in the comments, if you want a key that's missing in
bigdict
to map toNone
, you can do:If you're using Python 3, and you only want keys in the new dict that actually exist in the original one, you can use the fact to view objects implement some set operations:
至少短一点:
A bit shorter, at least:
对所有提到的方法进行一些速度比较:
于 2020 年 7 月 13 日更新(感谢@user3780389):
仅适用于来自 bigdict 的键。
正如预期的那样:字典理解是最好的选择。
A bit of speed comparison for all mentioned methods:
UPDATED on 2020.07.13 (thx to @user3780389):
ONLY for keys from bigdict.
As it was expected: dictionary comprehensions are the best option.
该答案使用与所选答案类似的字典理解,但不会排除缺少的项目。
python 2 版本:
python 3 版本:
This answer uses a dictionary comprehension similar to the selected answer, but will not except on a missing item.
python 2 version:
python 3 version:
如果您想保留大部分键并删除一些键,则可以采用另一种方法:
An alternative approach for if you want to retain the majority of the keys while removing a few:
也许:
Python 3 甚至支持以下内容:
请注意,您可以按如下方式检查字典中是否存在:
resp。对于Python 3
Maybe:
Python 3 even supports the following:
Note that you can check for existence in dictionary as follows:
resp. for python 3
您还可以使用
map
(无论如何,这是一个非常有用的函数):sd = dict(map(lambda k: (k, l. get(k, None)), l))
示例:
PS:我从之前的答案中借用了
.get(key, None)
:)You can also use
map
(which is a very useful function to get to know anyway):sd = dict(map(lambda k: (k, l.get(k, None)), l))
Example:
PS: I borrowed the
.get(key, None)
from a previous answer :)好吧,这个问题已经困扰了我好几次了,所以谢谢 Jayesh 的提问。
上面的答案似乎是一个很好的解决方案,但如果您在整个代码中使用它,那么包装功能恕我直言是有意义的。此外,这里有两种可能的用例:一种是您关心所有关键字是否都在原始字典中。还有一个你不知道的地方。平等对待两者就好了。
因此,对于我的二便士价值,我建议编写一个字典的子类,例如
现在您可以使用以下命令拉出一个子字典
用法示例:
如果运行上述所有代码,您应该看到(类似)以下输出(抱歉格式错误):
Okay, this is something that has bothered me a few times, so thank you Jayesh for asking it.
The answers above seem like as good a solution as any, but if you are using this all over your code, it makes sense to wrap the functionality IMHO. Also, there are two possible use cases here: one where you care about whether all keywords are in the original dictionary. and one where you don't. It would be nice to treat both equally.
So, for my two-penneth worth, I suggest writing a sub-class of dictionary, e.g.
Now you can pull out a sub-dictionary with
Usage examples:
If you run all the above code, you should see (something like) the following output (sorry for the formatting):
解决方案
使用示例
solution
examples of use
py3.8+ 中避免
big_dict
中缺少键的None
值的另一种方法是使用 walrus:Another way in py3.8+ that avoids
None
values for keys missing frombig_dict
uses the walrus:还有一个(我更喜欢Mark Longair的回答)
Yet another one (I prefer Mark Longair's answer)
使用地图(halfdanrump的答案)对我来说是最好的,虽然还没有计时......
但是如果你去找一本字典,并且如果你有一个big_dict:
所以例如:
请注意,在相反的情况下,req很大,但my_dict很小,你应该循环遍历my_dict。
一般来说,我们正在做一个交集,问题的复杂度是 O(min(len(dict)),min (len(req)))。 Python 的自己的交集实现考虑两个集合的大小,所以这看起来是最优的。此外,在 c 语言中并且是核心库的一部分,可能比大多数未优化的 python 语句更快。
因此,我会考虑的一个解决方案是:
它将关键操作移到 python 的 c 代码中,并且适用于所有情况。
Using map (halfdanrump's answer) is best for me, though haven't timed it...
But if you go for a dictionary, and if you have a big_dict:
so e.g.:
Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.
In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements.
Therefore, a solution that I would consider is:
It moves the critical operation inside python's c code and will work for all cases.
如果有人想要字典的前几项
n
而不知道键:In case someone wants first few items
n
of the dictionary without knowing the keys: