我有一些看起来像这样的代码:
@H_301_2@d = {'foo': True,'bar': 42,'baz': '!'}
a = {'foo': d['foo'],'bar': d['bar']}
b = {'foo': d['foo'],'baz': d['baz']}
c = {'bar': d['bar'],'baz': d['baz']}
当然有更好的方式来表达这一点.我实际上阅读了文档,希望字典的复制方法接受要包含在新字典中的键:
@H_301_2@# I'd hoped that something like this would work... a = d.copy('foo','bar') b = d.copy('foo','baz') c = d.copy('bar','baz')我可以为此目的编写一个函数:
@H_301_2@copydict = lambda dct,*keys: {key: dct[key] for key in keys} a = copydict(d,'foo','bar') b = copydict(d,'baz') c = copydict(d,'bar','baz')有没有比上面更好的解决方案?