我有一本字典和一個清單:
dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
remove = ['b', 'c', 'e']
我需要使用“洗掉”將“字典”分成兩個字典。這個想法是從“字典”中洗掉“洗掉”中的鍵,但我不想丟棄它們,而是想將它們保存在新字典中。我想要的結果是
old_dictionary = {'a':1, 'd':4, 'f':6}
new_dictionary = {'b':2, 'c':3, 'e':5}
獲取“new_dictionary”相當容易。
new_dictionary = {}
for key, value in dictionary.items():
if key in remove:
new_dictionary[key] = value
如何找到“dictionary”和“new_dictionary”之間的區別以獲得“old_dictionary”?我想我只能再次回圈,not in remove...但是對于類似于設定差異的字典有一個很好的技巧嗎?
uj5u.com熱心網友回復:
一種方法是dict.pop在回圈中使用:
new_dict = {k: dictionary.pop(k) for k in remove}
old_dict = dictionary.copy()
輸出:
>>> new_dict
{'b': 2, 'c': 3, 'e': 5}
>>> old_dict
{'a': 1, 'd': 4, 'f': 6}
uj5u.com熱心網友回復:
只需添加其他
new_dictionary = {}
old_dictionary = {}
for key, value in dictionary.items():
if key in remove:
new_dictionary[key] = value
else:
old_dictionary[key] = value
uj5u.com熱心網友回復:
用于else:將其放入其他字典。
new_dictionary = {}
old_dictionary = {}
for key, value in dictionary.items():
if key in remove:
new_dictionary[key] = value
else:
old_dictionary[key] = value
uj5u.com熱心網友回復:
dict.keys()ordict.items()可以像具有其他可迭代序列的集合一樣操作:
>>> dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
>>> remove = list('bce')
>>> new_dict = {key: dictionary[key] for key in remove}
>>> new_dict
{'b': 2, 'c': 3, 'e': 5}
>>> dict(dictionary.items() - new_dict.items())
{'d': 4, 'f': 6, 'a': 1}
但是,就性能而言,這種方法不如得分最高的答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/467203.html
標籤:Python python-3.x 字典
下一篇:如何為虛擬環境設定pip配置?
