Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 302
user3502285 Avatar asked Oct 18 '25 12:10

user3502285


1 Answers

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

like image 96
John La Rooy Avatar answered Oct 22 '25 05:10

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!