我有一些看起来像这样的代码:
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_5@
# I'd hoped that something like this would work... a = d.copy('foo','bar') b = d.copy('foo','baz') c = d.copy('bar','baz')
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')