0

I have two defaultdicts and essentially I want to see if the values on both dictionaries match up for the same corresponding keys. For example: {1,4} {1,4}. So it looks for matching keys which is 1 and then checks to see if their value match up 4 which it does.

So in my case I have:

keyOne = [30, 30, 60, 70, 90]
valueOne = [3, 4, 6, 7, 0]

KeyTwo = [30, 30, 60, 70, 90]
valueTwo = [4, 5, 6, -10, 9]

I create two defaultdicts as such:

one = defaultdict(list)
for k, v in zip(keyOne, valueOne):
   one[k].append(v)

two = defaultdict(list)
for k, v in zip(keyTwo, valueTwo):
   two[k].append(v)

I then want to add the entries where the keys match but the values don't - so I write this, but it doesn't work:

three = defaultdict(list)

for k,v in one.items():
  for key in k:
    if key in two.items():
      if (value != v):
        three[k].append(value)

I am not sure where I am going wrong and it would mean a lot if someone could help me fix it. I'm new to programming and really want to learn

benvc
  • 14,448
  • 4
  • 33
  • 54

1 Answers1

0

You got a typo and can simplify your loop:

from collections import defaultdict

keyOne = [30, 30, 60, 70, 90]
valueOne = [3, 4, 6, 7, 0]

keyTwo = [30, 30, 60, 70, 90]   # typo KeyTwo
valueTwo = [4, 5, 6, -10, 9] 

one = defaultdict(list)
for k, v in zip(keyOne, valueOne):
   one[k].append(v)

two = defaultdict(list)
for k, v in zip(keyTwo, valueTwo):
   two[k].append(v)
three = defaultdict(list)

for k1,v1 in one.items():   # there is no need for a double loop if you just want
    v2 = two.get(k1)        # to check the keys that are duplicate - simply query
    if v2:                  # the dict 'two' for this key and see if it has value
        three[k1] = [value for value in v2 if value not in v1]

    # delete key again if empty list (or create a temp list and only add if non empty)
    if not three[k1]:
        del three[k1]

print(three)

Output:

# all values in `two` for "keys" in `one` that are not values of `one[key]`
defaultdict(<class 'list'>, {30: [5], 70: [-10], 90: [9]})

Using dict.get(key) returns None if the key is not in the dictionary and eliminates the if - checking before retrieval. You still need the if afterwards though - but I think this code is "cleaner".

See Why dict.get(key) instead of dict[key]?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69