简体   繁体   English

python 条件字典和替换

[英]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.我有一个条件字典,当通过 function 识别字符串时,它返回该字典的键。

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. dict是“myDict”,它将与列表“lookup”一起使用,找到其中存在的单词,并返回该列表的字典键,将其添加到该名称的末尾。

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 NESTLE 无 无 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,并且它没有搜索其中包含的所有单词,因此我想要这个 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这是我得到的 output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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