从另一个字典值替换字典值

时间:2018-11-07 03:01:30

标签: python

我有两个字典,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.']}

我对此很困惑。指导手将不胜感激!

1 个答案:

答案 0 :(得分:1)

尝试dict理解:

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.']}