gpt4 book ai didi

python - 将字典值替换为另一个字典值

转载 作者:行者123 更新时间:2023-12-01 08:49:31 31 4
gpt4 key购买 nike

我有两个字典,First_DictSecond_Dict:

First_Dict = {'Texas': 'Austin', 'California': 'San Diego', 'Florida': 'Miami', 
'Arizona': 'Phoenix'}

Second_Dict = {'Family1': ['This family went to Arizona.'], 'Family2': ['This
family went to Texas.'], 'Family3': ['This family went to California.']}

目标:对于 Second_Dict 中提到的每个状态,我需要将该值与 First_Dict 上的键相匹配。如果存在匹配项,请将 Second_Dict 的值替换为 First_Dict 键中的值。

所以输出将如下所示:

Second_Dict = {'Family1': ['This family went to Phoenix.'], 'Family2': 
['This family went to Austin.'], 'Family3': ['This family went to
San Diego.']}

我被这个问题难住了。非常感谢您的指导!

最佳答案

尝试字典理解:

import re
print({k:[' '.join([First_Dict.get(re.sub('[^a-zA-Z]','',i),i) for i in v[0].split()])+'.'] for k,v in Second_Dict.items()})

输出:

{'Family1': ['This family went to Phoenix.'], 'Family2': ['This family went to Austin.'], 'Family3': ['This family went to San Diego.']}

更新:

Second_Dict = {k:[' '.join([First_Dict.get(re.sub('[^a-zA-Z]','',i),i) for i in v[0].split()])+'.'] for k,v in Second_Dict.items()}

现在 Second_Dict 是字典,

所以:

print(Second_Dict)

是:

{'Family1': ['This family went to Phoenix.'], 'Family2': ['This family went to Austin.'], 'Family3': ['This family went to San Diego.']}

关于python - 将字典值替换为另一个字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53183042/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com