Search code examples
pythondictionarykeystartswith

How to check if a key in a dictionary startswith the a key in another dictionary?


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

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