0
dict1 = {
    key1: value1,
    key2: value2,
    key3: value3
}

dict2 = {
    key1: value1,
    key4: value4,
    key3: value2
}
fdict = {}

when I compare the above two dictionaries, I want to store key1: value1 to fdict dictionary:

my attempt:

for key in dict1.keys():
    if key in dict2.keys():
        if dict1[key] == dict2[key]:
            fdict[key] == dict1[key]

I am having "key error" when I tried above method.. any suggestions?

DevBabai
  • 83
  • 12
  • 1
    where are `content` and `new_dict` defined? – pault Jul 26 '18 at 16:57
  • well, as it sits, none of your keys exist because you didnt provide variables or you didn't surround with quotes – dfundako Jul 26 '18 at 16:57
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Your posted code has syntax and semantic errors that prevent it from reaching the error state you posted. – Prune Jul 26 '18 at 16:58
  • Besides the [great answer below](https://meta.stackexchange.com/a/5235) You can also check [this one](https://stackoverflow.com/a/49710152/2996101). – raratiru Jul 26 '18 at 17:05
  • Are you sure that `fdict` contains `key` that you try to compare? P.S. Replace `==` to `=` in last line, if I correctly understand you needs. – Gordio Jul 27 '18 at 00:46

1 Answers1

7

Well, for one, you get KeyError because you try to look up keys which don't exist in both dicionaries.

It sounds to me like you want to compute an intersection of two dictionaries. In such case, it's enough to:

>>> a = dict(a=1, b=2, c=3)
>>> b = dict(b=2, c=3, d=4)
>>> dict(a.items() & b.items())
{'c': 3, 'b': 2}
Siegmeyer
  • 4,312
  • 6
  • 26
  • 43