2

I have two sets of dictionaries. Let's call them A and B. I need to be able to create a third dictionary, C, which has all the keys and associated values of A, except for the pairs that are in B. This is what I have tried so far:

A = {"A": {"B": 6, "C": 5}, "B": {"A": 6, "D": 7, "E": 5}, "C": {"A": 5}, "D": {"B": 7, "E": 10, "H": 25},
     "E": {"D": 10, "F": 14, "B": 5}, "F": {"E": 14}, "H": {"D": 25}}
B = {"A": "C"}

C = A

for key, value in A.items():
     C.update({key: value})
     if key in B:
          for i in value:
               if i not in B.values():
                    C[key].pop(i)

print(C)

The idea is, given the two dictionaries, to obtain the output:

A = {"A": {"B": 6}, "B": {"A": 6, "D": 7, "E": 5}, "C": {"A": 5}, "D": {"B": 7, "E": 10, "H": 25}, "E": {"D": 10, "F": 14, "B": 5}, "F": {"E": 14}, "H": {"D": 25}}

Instead, the terminal returns an error, saying that the dictionary has changed size during the iteration. What exactly am I doing wrong here?

1
  • Do you really want if i not in B.values():? I would have expected if i != B[key]:, and subsequently optimised away the for i in value: loop by only looking for B[key] in value
    – Bergi
    Jun 4 at 16:37

2 Answers 2

1

You can use dict comprehension:

A = {
    "A": {"B": 6, "C": 5},
    "B": {"A": 6, "D": 7, "E": 5},
    "C": {"A": 5},
    "D": {"B": 7, "E": 10, "H": 25},
    "E": {"D": 10, "F": 14, "B": 5},
    "F": {"E": 14},
    "H": {"D": 25},
}
B = {"A": "C"}

C = {
    k: {kk: vv for kk, vv in v.items() if not (k in B and B[k] == kk)}
    for k, v in A.items()
}
print(C)

Prints:

{
    "A": {"B": 6},
    "B": {"A": 6, "D": 7, "E": 5},
    "C": {"A": 5},
    "D": {"B": 7, "E": 10, "H": 25},
    "E": {"D": 10, "F": 14, "B": 5},
    "F": {"E": 14},
    "H": {"D": 25},
}
0

I think you want:

import pprint

A = {
    "A": {"B": 6, "C": 5},
    "B": {"A": 6, "D": 7, "E": 5},
    "C": {"A": 5},
    "D": {"B": 7, "E": 10, "H": 25},
    "E": {"D": 10, "F": 14, "B": 5},
    "F": {"E": 14},
    "H": {"D": 25},
}
B = {"A": "C"}
C = {}

for k, v in A.items():
    for kk, vv in v.items():
        if k in B and B[k] == kk:
            continue

        C.setdefault(k, {})[kk] = vv

pprint.pprint(C)

Which given your sample input produces:

{'A': {'B': 6},
 'B': {'A': 6, 'D': 7, 'E': 5},
 'C': {'A': 5},
 'D': {'B': 7, 'E': 10, 'H': 25},
 'E': {'B': 5, 'D': 10, 'F': 14},
 'F': {'E': 14},
 'H': {'D': 25}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.