当满足特定条件时从字典中分离记录,并使用该字典替换字符串中的单词

Seperate records from a dictionary when a specific condition is met, and use that dictionary for replacing words in string

第一个问题

我准备好了字典。我想根据特定的键值对分隔记录。 例子

dict = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

这里我想将记录分叉到其他具有相同颜色的字典中 所以我希望输出是这样的

dict_red_color = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

dict_yellow_color = [{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'}]

第二个问题(代码已准备就绪,但使用的是单个字典)

import re

txt = "<I love *NAME*, it is *COLOR* in color, Its price is *PRICE*>"

dict = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

pattern = r"\*([^*]+)\*"

for d in dicts:
    print(re.sub(pattern, lambda match: d[match[1]], txt))

输出是

"<I love APPLE, it is RED in color, Its price is 100>
 <I love MANGO, it is YELLOW in color, Its price is 300>"

这段代码只考虑一个文本字符串和一个字典,我想做同样的事情,首先将字典分成两部分,然后我们将在第一个问题中制作的那两个字典将与他们一起使用各自的文本字符串,它们是:

text_for_red_color = ''' <I love *NAME*, the price is *PRICE* > '''
text_for_yellow_color = ''' <I don't love *NAME*, the price is *PRICE* > '''

2 部词典,

dict_red_color = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

dict_yellow_color = [{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'}]

将最终输出创建为,

output = ''' <I love Apple, the price is 100><I love Cherry, the price is 250><I don't love Mango, the price is 300> '''

你的第一个问题

dict_red_color = [x for x in dict if x["COLOR"] == "RED"]
dict_yellow_color = [x for x in dict if x["COLOR"] == "YELLOW"]

为什么要在这里使用 re?为什么不使用字符串格式?至于根据颜色过滤文本,使用以颜色为键、以字符串为值的字典:

inputs = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

outputs = {'RED': "<I love {NAME}, the price is {PRICE} >", 'YELLOW': "<I don't love {NAME}, the price is {PRICE} >"}

for d in inputs:
    print(outputs[d['COLOR']].format(**d))

输出:

<I love APPLE, the price is 100 >
<I don't love MANGO, the price is 300 >
<I love CHERRY, the price is 250 >