以Pythonic的方式将字典作为输入,返回一个子字典作为输出

2024-04-20 10:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种最具python风格的方法,将一个字典和一个键名作为输入,并返回没有键(和相关值)作为输出的字典。你知道吗

到目前为止我想到的是:

def SubDict(inputDict,inputkey):
    return dict([(key,val) for key,val in inputDict.iteritems() if key != inputkey])

测试用例:

print SubDict({'a':1,'b':2,'c':3},'b')

提供:

{'a': 1, 'c': 3}

有没有更好的建议(更干净和/或更简单的代码)?你知道吗

谢谢你。你知道吗


Tags: 方法keyinforreturn字典风格def
2条回答

另一种方法是:

d = {'a': 1, 'b': 2, 'c': 3}

def filtered_dict(inputdict, inputkey):
    return dict(zip(filter(lambda x: x != inputkey, inputdict), inputdict.values()))

{'a': 1, 'c': 3}


%timeit SubDict(d, 'b')
The slowest run took 10.13 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 306 ns per loop


%timeit filtered_dict(d, 'b')
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.02 µs per loop

好吧,你的理解也可以换成dictionary display

{key:val for key,val in inputDict.iteritems() if key != inputkey}

但实际上,复制和删除可能更快,因为查找是O(1)。由于过滤器的存在,Python不会提前知道字典的大小,哈希表的增长可能会非常昂贵。你知道吗

def SubDict(inputDict, inputkey):
    subdict = inputDict.copy()
    del subdict[inputkey]
    return subdict

这也是相当可读的。你知道吗

如果您想在找不到inputkey时忽略大小写,可以用subdict.pop(inputkey, None)替换del。这提供了一个默认值(我们忽略了),而不是进行双重检查。你知道吗

相关问题 更多 >