如果两个元组元素都不在其他字典键中,则删除元组键字典条目

时间:2020-01-27 02:39:18

标签: python dictionary tuples

我有一本以元组为键的字典。
还有第二本带有单个元素键的字典。
值无关紧要。

dictionary_1 = {("Apple","Banana") : 3,
                 ("Cat","Dog") : 5,
                 ("Spain", "Italy") : 10,
                 ("Chair","Sofa"): 23}

dictionary_2 = {"Denmark" : 4,
                "Apple" : 9,
                "Fish" : 7,
                "Sofa" : 8 }

如果键的任一元素是Dictionary_2中的键之一,我想从dictionary_1中删除键

因此解决方案是:

#Some code
print(dictionary_1)
#The remaining key value pairs would be:
{("Cat","Dog") : 5,
 ("Spain", "Italy") : 10}

谢谢!

5 个答案:

答案 0 :(得分:2)

使用dictionary comprehensionsets可以使此问题的工作很短暂:

>>> dictionary_1 = {fruits: n 
                    for fruits, n in dictionary_1.items()
                    if set(fruits).isdisjoint(dictionary_2)}
{('Cat', 'Dog'): 5, ('Spain', 'Italy'): 10}

这说:

  • dictionary_1 重新分配给映射到数字的新的元组字典
  • 从原始词典的项目中获取键/值对
  • 仅包括该对,因为水果元组和第二个字典的键之间没有重叠。

希望这会有所帮助:-)

答案 1 :(得分:1)

您可以使用for key in dict语法来迭代字典的键:

dictionary_1 = {("Apple","Banana") : 3,
                 ("Cat","Dog") : 5,
                 ("Spain", "Italy") : 10,
                 ("Chair","Sofa"): 23}

dictionary_2 = {"Denmark" : 4,
                "Apple" : 9,
                "Fish" : 7,
                "Sofa" : 8 }

new_dict = {}
for i in dictionary_1:
    if i[0] not in dictionary_2 and i[1] not in dictionary_2:
        new_dict[i] = dictionary_1[i]

print(new_dict) # {('Spain', 'Italy'): 10, ('Cat', 'Dog'): 5}

答案 2 :(得分:1)

您可以使用dict理解来制作新词典并利用some()进行测试:

dictionary_1 = {("Apple","Banana") : 3,
                 ("Cat","Dog") : 5,
                 ("Spain", "Italy") : 10,
                 ("Chair","Sofa"): 23}

dictionary_2 = {"Denmark" : 4,
                "Apple" : 9,
                "Fish" : 7,
                "Sofa" : 8 }

{k:v for k,v in dictionary_1.items() 
 if not any(t in dictionary_2 for t in k)}
# {('Cat', 'Dog'): 5, ('Spain', 'Italy'): 10}

答案 3 :(得分:0)

您可以简单地遍历字典键:

ret = {}
for x, y in dictionary_1:
    if x not in dictionary_2 and y in dictionary_2:
       ret[(x, y)] = dictionary_1[x, y]

答案 4 :(得分:0)

关于字典理解的另一个建议:

dictionary_1 = {("Apple","Banana") : 3,
                ("Cat","Dog") : 5,
                ("Spain", "Italy") : 10,
                ("Chair","Sofa"): 23}

dictionary_2 = {"Denmark" : 4,
                "Apple" : 9,
                "Fish" : 7,
                "Sofa" : 8 }

result = {(k1, k2): dictionary_1[k1, k2] for k1, k2 in dictionary_1 if k1 not in dictionary_2 and k2 not in dictionary_2}

print(result)

# output: {('Cat', 'Dog'): 5, ('Spain', 'Italy'): 10}