【问题标题】:Delete (a, b) in dictionary_1 if a in dictionary_2如果 a 在 dictionary_2 中,则删除 dictionary_1 中的 (a, b)
【发布时间】:2022-01-24 18:04:00
【问题描述】:

我有两本字典

D1 = {('one', 'two'): 3, ('three', 'four'): 5, ('five', 'six'): 7, ('eight', 'nigh'):8} 
D2 = {'one':1, 'five': 2}

我想删除 D1 中的 ('one', 'two'): 3('five', 'six'): 7,因为 D2 包含“一”和“五”。

【问题讨论】:

  • 你尝试过什么,它到底有什么问题?

标签: python dictionary


【解决方案1】:

您可以像这样遍历字典中的键:

for key in my_dict:
    do_something_with_key()

您可以通过删除键从字典中删除项目。 因此,您的问题的一种解决方案是:

for key in D2:
    del(D1[key])

【讨论】:

    【解决方案2】:

    实现此目的的一种方法是使用dict 推导式构造一个新字典D3,其中不包含其键存在于D2 中的元素。这通过排除其元组与D2 的键共享元素的元素来工作。他的比较是在D1 的每个键的元素集和D2 的键集之间使用set 交集& 进行的。

    D1 = {('one', 'two'): 3, ('three', 'four'): 5, ('five', 'six'): 7, ('eight', 'nigh'):8} 
    D2 = {'one':1, 'five': 2}
    
    
    D3 = {k: v for k, v in D1.items() if not set(k) & set(D2)}
    print(D3)
    

    输出:

    {('three', 'four'): 5, ('eight', 'nigh'): 8}
    

    【讨论】:

    • 有效!谢谢!
    【解决方案3】:

    正如 MichaelCG8 所建议的,您需要通过迭代来访问字典中的键。

    主要思想是你需要检查 D2 中的一个键是否存在于作为 D1 键的元组中。明白了思路后,一定要自己解决问题!

    您可以这样做的一种方法是:

    to_remove = []
    
    for key in D2.keys():
        for tup in D1.keys():
            if key in tup:
                to_remove.append(tup)
    
    for remove in to_remove:
        del(D1[remove])
    
    print(D1)
    

    在上面的代码中,我们检查所有符合您条件的键,将它们放入一个列表中,然后将它们从 D1 中删除。

    输出:

    {('three', 'four'): 5, ('eight', 'nigh'): 8}

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多