1

I am new to coding and I am looking to code a function (max_dict) that takes two dictionaries and creates a third dictionary that includes only keys and values where the key was contained in both dictionaries. The code below works, but I want a more efficient way to do it! Thanks!

def max_dict(dict1, dict2):
    new_dict = {}
    for key, value in dict1.items():
        for k, v in dict2.items():
            if key == k:
                new_dict[key] = value
    return new_dict
Chelsea
  • 96
  • 1
  • 1
  • 7
  • 1
    _third dictionary that includes only keys and **values**_, yet you take only value from dict1, what should happen with value from dict2? – buran Feb 16 '22 at 19:45
  • Have a look at https://stackoverflow.com/questions/18554012/intersecting-two-dictionaries and similar. – PM 77-1 Feb 16 '22 at 19:47
  • @buran has a point; are you trying to save a value from dict1 or dict2 OR: do you mean you ONLY want keys that match BOTH the key AND the value? – Shawn Ramirez Feb 16 '22 at 19:55

2 Answers2

1

Something like this should work

new_dict = {x:dict1[x] for x in dict1 if x in dict2}
stefan_aus_hannover
  • 1,777
  • 12
  • 13
0

How about this?

def max_dict(dict1, dict2):
    new_dict = {}
    for key in dict1:
        if (key in dict2 and dict1[key] == dict2[key]):
            new_dict[key]=dict1[key]
    return new_dict
Shawn Ramirez
  • 796
  • 1
  • 5
  • 10