在Python中从字典中删除键并返回新字典 [英] Remove key from dictionary in Python returning new dictionary
本文介绍了在Python中从字典中删除键并返回新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字典
d = {'a':1, 'b':2, 'c':3}
我需要删除一个键,说 c 并在一个函数调用中返回没有该键的字典
I need to remove a key, say c and return the dictionary without that key in one function call
{'a':1, 'b':2}
d.pop('c')将返回键值-3-而不是字典.
d.pop('c') will return the key value - 3 - instead of the dictionary.
如果有的话,我将需要一个函数解决方案,因为这会引起理解
推荐答案
这是怎么回事:
{i:d[i] for i in d if i!='c'}
它称为词典理解,自Python 2.7起可用.
It's called Dictionary Comprehensions and it's available since Python 2.7.
或者如果您使用的是2.7之前的Python:
or if you are using Python older than 2.7:
dict((i,d[i]) for i in d if i!='c')
这篇关于在Python中从字典中删除键并返回新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文