4

Here is a simplified scenario of what I am trying to do. I have two dictionaries:

dictA = {"apple": 1, "orange": 2, "chocolate": 3, "mango": 4}
dictB = {"man": "abc", "or": "asdf", "app": "fasdfkl"}

How do I make it print (The actual order of the three keys+values do not matter):

I can find...
orange2
mango4
apple1

I cannot find...
chocolate3

I have attempted to do something like this but got stuck on the second part.

print "I can find ..."
for itemA in dictA:
    for itemB in dictB:
        if itemA.startswith(itemB):
            print itemA + str(dictA[itemA])

It would print

I can find ...
orange2
mango4
apple1
Savir
  • 17,568
  • 15
  • 82
  • 136
user3502285
  • 277
  • 5
  • 14
  • 1
    It seems that your code does exactly what you want it to find. There is no key in `dictB` that starts with a `c`; therefore `chocolate3` should never be found, and it isn't. What is your actual question? – inspectorG4dget Apr 05 '14 at 21:58
  • @inspectorG4dget, I think it's supposed to use another loop to print the ones it can't find. – John La Rooy Apr 05 '14 at 22:04

2 Answers2

5

Start by simplifing the first loop to this

print "I can find ..."
for itemA in dictA:
    if any(itemA.startswith(itemB) for itemB in dictB):
        print itemA + str(dictA[itemA])

The second loop would use if not any(...)

This isn't a very efficient algorithm, but I guess you are just doing an exercise

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Hi gribbler, an extension to this question. How could I do it if I want to "print itemA + itemB" instead of "print itemA + str(dictA[itemA])" in the case above? I am getting "itemB is not defined" when I tried modifying your suggestion accordingly. – user3502285 Apr 07 '14 at 15:35
  • @user3502285, you'd need to change the first loop back to the form you originally had it. I don't think it makes sense to print any itemB in the second loop – John La Rooy Apr 07 '14 at 19:33
0

I'd keep track of the keys that you found and output the ones you didn't find in the end:

dictA = {"apple": 1, "orange": 2, "chocolate": 3, "mango": 4}
dictB = {"man": "abc", "or": "asdf", "app": "fasdfkl"}
found_keys = set()

for key_b in dictB.keys():
  for key_a in dictA.keys():
    if key_a.startswith(key_b):
      print "I can find: %s %s" % (key_a, dictA[key_a])
      found_keys.add(key_a)
      break
print "I couldn't find: %s" % dict((k, dictA[k]) for k in set(dictA.keys()) - found_keys)

That outputs:

I can find: apple 1
I can find: orange 2
I can find: mango 4
I couldn't find: {'chocolate': 3}

EDIT: I just saw gnibbler's answer. I like it more than mine, although since mine doesn't use any and explicitly calls the keys() method of the dict object, it may be a bit easier to understand (but, again, if you get what gnibbler's answer does, go with that one)

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136