如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
当前回答
在Python 3中,“dict”对象没有属性“remove”。
但使用immutables包,可以执行允许对Map对象应用更改并创建新的(派生的)Maps的突变:
import immutables
map = immutables.Map(a=1, b=2)
map1 = map.delete('b')
print(map, map1)
# will print:
# <immutables.Map({'b': 2, 'a': 1})>
# <immutables.Map({'a': 1})>
其他回答
d = {1: 2, '2': 3, 5: 7}
del d[5]
print 'd = ', d
结果:d={1:2,“2”:3}
下面的代码片段肯定会帮助您,我在每行中都添加了注释,这将帮助您理解代码。
def execute():
dic = {'a':1,'b':2}
dic2 = remove_key_from_dict(dic, 'b')
print(dict2) # {'a': 1}
print(dict) # {'a':1,'b':2}
def remove_key_from_dict(dictionary_to_use, key_to_delete):
copy_of_dict = dict(dictionary_to_use) # creating clone/copy of the dictionary
if key_to_delete in copy_of_dict : # checking given key is present in the dictionary
del copy_of_dict [key_to_delete] # deleting the key from the dictionary
return copy_of_dict # returning the final dictionary
或者也可以使用dict.pop()
d = {"a": 1, "b": 2}
res = d.pop("c") # No `KeyError` here
print (res) # this line will not execute
或者更好的方法是
res = d.pop("c", "key not found")
print (res) # key not found
print (d) # {"a": 1, "b": 2}
res = d.pop("b", "key not found")
print (res) # 2
print (d) # {"a": 1}
下面是使用列表理解的另一种变体:
original_d = {'a': None, 'b': 'Some'}
d = dict((k,v) for k, v in original_d.iteritems() if v)
# result should be {'b': 'Some'}
该方法基于本文中的答案:从字典中删除带有空字符串的键的有效方法
对于Python 3,这是
original_d = {'a': None, 'b': 'Some'}
d = dict((k,v) for k, v in original_d.items() if v)
print(d)
在Python 3中,“dict”对象没有属性“remove”。
但使用immutables包,可以执行允许对Map对象应用更改并创建新的(派生的)Maps的突变:
import immutables
map = immutables.Map(a=1, b=2)
map1 = map.delete('b')
print(map, map1)
# will print:
# <immutables.Map({'b': 2, 'a': 1})>
# <immutables.Map({'a': 1})>
可以试试我的方法。在一行。
yourList = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]
resultList = [{'key':dic['key']} for dic in yourList if 'key' in dic]
print(resultList)