我有一个大字典对象,它有几个键值对(大约16个),但我只对其中3个感兴趣。将这样的字典子集化的最佳方法(最短/有效/最优雅)是什么?
我知道的最好的是:
bigdict = {'a':1,'b':2,....,'z':26}
subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']}
我相信有比这更优雅的方式。
我有一个大字典对象,它有几个键值对(大约16个),但我只对其中3个感兴趣。将这样的字典子集化的最佳方法(最短/有效/最优雅)是什么?
我知道的最好的是:
bigdict = {'a':1,'b':2,....,'z':26}
subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']}
我相信有比这更优雅的方式。
当前回答
至少要短一点:
wanted_keys = ['l', 'm', 'n'] # The keys you want
dict((k, bigdict[k]) for k in wanted_keys if k in bigdict)
其他回答
解决方案
from operator import itemgetter
from typing import List, Dict, Union
def subdict(d: Union[Dict, List], columns: List[str]) -> Union[Dict, List[Dict]]:
"""Return a dict or list of dicts with subset of
columns from the d argument.
"""
getter = itemgetter(*columns)
if isinstance(d, list):
result = []
for subset in map(getter, d):
record = dict(zip(columns, subset))
result.append(record)
return result
elif isinstance(d, dict):
return dict(zip(columns, getter(d)))
raise ValueError('Unsupported type for `d`')
使用实例
# pure dict
d = dict(a=1, b=2, c=3)
print(subdict(d, ['a', 'c']))
>>> In [5]: {'a': 1, 'c': 3}
# list of dicts
d = [
dict(a=1, b=2, c=3),
dict(a=2, b=4, c=6),
dict(a=4, b=8, c=12),
]
print(subdict(d, ['a', 'c']))
>>> In [5]: [{'a': 1, 'c': 3}, {'a': 2, 'c': 6}, {'a': 4, 'c': 12}]
如果你想保留大部分键,同时删除一些键,另一种方法是:
{k: bigdict[k] for k in bigdict.keys() if k not in ['l', 'm', 'n']}
好吧,这个问题已经困扰过我几次了,谢谢你的提问。
上面的答案似乎是一个很好的解决方案,但如果你在你的代码中使用它,我认为包装功能是有意义的。此外,这里有两个可能的用例:一个是关心是否所有关键字都在原始字典中。还有一个你不知道的地方。如果能对两者一视同仁就好了。
所以,为了我的二分之一的价值,我建议写一个字典的子类,例如。
class my_dict(dict):
def subdict(self, keywords, fragile=False):
d = {}
for k in keywords:
try:
d[k] = self[k]
except KeyError:
if fragile:
raise
return d
现在您可以使用orig_dict.subdict(关键字)提取子字典
使用例子:
#
## our keywords are letters of the alphabet
keywords = 'abcdefghijklmnopqrstuvwxyz'
#
## our dictionary maps letters to their index
d = my_dict([(k,i) for i,k in enumerate(keywords)])
print('Original dictionary:\n%r\n\n' % (d,))
#
## constructing a sub-dictionary with good keywords
oddkeywords = keywords[::2]
subd = d.subdict(oddkeywords)
print('Dictionary from odd numbered keys:\n%r\n\n' % (subd,))
#
## constructing a sub-dictionary with mixture of good and bad keywords
somebadkeywords = keywords[1::2] + 'A'
try:
subd2 = d.subdict(somebadkeywords)
print("We shouldn't see this message")
except KeyError:
print("subd2 construction fails:")
print("\toriginal dictionary doesn't contain some keys\n\n")
#
## Trying again with fragile set to false
try:
subd3 = d.subdict(somebadkeywords, fragile=False)
print('Dictionary constructed using some bad keys:\n%r\n\n' % (subd3,))
except KeyError:
print("We shouldn't see this message")
如果你运行上面所有的代码,你应该会看到(类似于)下面的输出(抱歉格式化):
Original dictionary: {'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 12, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v': 21, 'y': 24, 'x': 23, 'z': 25} Dictionary from odd numbered keys: {'a': 0, 'c': 2, 'e': 4, 'g': 6, 'i': 8, 'k': 10, 'm': 12, 'o': 14, 'q': 16, 's': 18, 'u': 20, 'w': 22, 'y': 24} subd2 construction fails: original dictionary doesn't contain some keys Dictionary constructed using some bad keys: {'b': 1, 'd': 3, 'f': 5, 'h': 7, 'j': 9, 'l': 11, 'n': 13, 'p': 15, 'r': 17, 't': 19, 'v': 21, 'x': 23, 'z': 25}
interesting_keys = ('l', 'm', 'n')
subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict}
可能:
subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n']])
Python 3甚至支持以下内容:
subdict={a:bigdict[a] for a in ['l','m','n']}
注意你可以在字典中检查是否存在,如下所示:
subdict=dict([(x,bigdict[x]) for x in ['l', 'm', 'n'] if x in bigdict])
分别地。对于python 3
subdict={a:bigdict[a] for a in ['l','m','n'] if a in bigdict}