Question

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
Was it helpful?

Solution

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

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top