简体   繁体   中英

python conditional dictionary and replace

I have a conditional dict, when a string is recognized thorugh a function, it returns the key of that dictionary.

The dict is "myDict", which will be use together with the list "lookup", find a word that exists in it, and return the dictionary key for that list, adding it to the end of that name.

My code:

  myDict = {'NESTLE':
                  ['NESFIT', 'NESCAU', 'DOIS FRADES', 'MOCA', 'KIT KAT', 'NESQUIK', 'ALPINO', 'LEITE CONDENSADO MOCA'
                  'CHAMYTO', 'NINHO', 'MOLICO', 'CHAMBINHO', 'CHANDELLE', 'BONO', 'PASSATEMPO', 'KITKAT', 'CLASSIC'],
                'all_names': ['rodis', 'Stone', 'abx']}
    
    def search(myDict, lookup):
        for key, value in myDict.items():
            for v in value:
                if lookup in v:
                    return key
    
    lookup = ['NESCAU', 'Confeito coberto de chocolate ao leite NESCAU Ball', 'NESCAU EM PO', 'Stone']
    lookup2 = [str(x).split(' ') for x in lookup]
    
    for x in range(0, len(lookup)):
        finder = search(myDict, lookup[x])
        print(finder)

NESTLE None None all_names

I arrived here, but was unable to do this output with the dictinary's key at the end of the list, and it is not searching for all words that contains in it, thus I wanted this output:

output_lookup = ['NESCAU NESTLE', 'Confeito coberto de chocolate ao leite NESCAU Ball NESTLE', 'NESCAU EM PO NESTLE', 'Stone all_names']

I changed your code.

I added a split of the lookup string.


myDict = {'NESTLE':
                  ['NESFIT', 'NESCAU', 'DOIS FRADES', 'MOCA', 'KIT KAT', 'NESQUIK', 'ALPINO', 'LEITE CONDENSADO MOCA'
                  'CHAMYTO', 'NINHO', 'MOLICO', 'CHAMBINHO', 'CHANDELLE', 'BONO', 'PASSATEMPO', 'KITKAT', 'CLASSIC'],
                'all_names': ['rodis', 'Stone', 'abx']}

def search(myDict, lookup):
        for key, value in myDict.items():
            for v in value:
#                if lookup in v:
                if v in lookup.split(' '):
                    return key

lookup = ['NESCAU', 'Confeito coberto de chocolate ao leite NESCAU Ball', 'NESCAU EM PO', 'Stone']
lookup2 = [str(x).split(' ') for x in lookup]

for x in lookup:
        finder = search(myDict, x)
        print(f"{x} {finder}")

Here the output that i got

NESCAU NESTLE
Confeito coberto de chocolate ao leite NESCAU Ball NESTLE
NESCAU EM PO NESTLE
Stone all_names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM