vmx1987
vmx1987

Reputation: 51

Replace dictionary value from another dictionary value

I have two dictionaries, First_Dict and Second_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.']}

Goal: For every state mentioned in Second_Dict, I need to match that value to the key on First_Dict. If there's a match, replace the Second_Dict's value with the value from the First_Dict key.

So the output would look like this:

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

I'm stumped on this one. A guiding hand would be highly appreciated!

Upvotes: 1

Views: 101

Answers (1)

U13-Forward
U13-Forward

Reputation: 71580

Try dict comprehension:

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()})

Output:

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

Update:

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()}

And then now Second_Dict is the dictionary,

So:

print(Second_Dict)

Is:

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

Upvotes: 1

Related Questions