[英]Python - Removing item from dictionary if first tuple key not in other dictionary
我有兩本字典D1
, D2
。 D1
包含一個鍵,后跟一個值。 D2
包含一個元組作為鍵,后跟一個值。
D1 = {'x':123, 'x1': 154, 'x2':184}
D2 = {('x','x1'):50, ('x1','x2'):30, ('y','x2'):10}
如果元組鍵的第一部分不是D1
中的鍵,有沒有辦法從D2
中刪除一個項目? 因此,在此示例中,應從字典中刪除D2
中以“y”作為第一個元組鍵值的項目。 所以D2
看起來像這樣。
D2 = {('x','x1'):50, ('x1','x2'):30}
您可以嘗試迭代 D2.items():
D1 = {'x':123, 'x1': 154, 'x2':184}
D2 = {('x','x1'):50, ('x1','x2'):30, ('y','x2'):10}
new_dict = {i:j for i,j in D2.items() if i[0] in D1}
print(new_dict)
輸出
{('x', 'x1'): 50, ('x1', 'x2'): 30}
使用.copy()
復制D2
並對其進行迭代,以避免在執行.pop()
時改變原始字典並獲得RuntimeError
D1 = {'x':123, 'x1': 154, 'x2':184}
D2 = {('x','x1'):50, ('x1','x2'):30, ('y','x2'):10}
for i in D2.copy():
if i[0] not in D1.keys():
D2.pop(i)
D2 變為:
{('x', 'x1'): 50, ('x1', 'x2'): 30}
執行此操作的簡單功能:
D1 = {'x':123, 'x1': 154, 'x2':184}
D2 = {('x','x1'):50, ('x1','x2'):30, ('y','x2'):10}
def remove_keys(d1, d2):
keys_list = d1.keys()
keys_to_remove = []
for k1, k2 in d2.keys():
if k1 not in keys_list:
keys_to_remove.append((k1, k2))
for key in keys_to_remove:
del d2[key]
return d2
D2 = remove_keys(D1, D2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.