0

There are two dictionaries that I would like to map.

These the are the key's and values inside my 1st dictionary:

first = {
    "Name": " John Doe", 
    "Gender": "Male", 
    "Phone": "01 9672 0321",
    "Occupation": "Engineer",  
}

2nd dictionary:

second = {
    "First_Name": "Name",
    "Last_Name": "Name",
    "Gender": "Gender", 
    "Phone": "Phone",
    "Occupation": "Occupation",
}

The Output should be:

"FirstName": "John",
"LastName": "Doe",
"Gender": "Male", 
"Phone": "01 9672 0321",
"Occupation": "Engineer"

I am new to Python and I am confused how to do this.

user2390182
  • 72,016
  • 6
  • 67
  • 89
jia
  • 11
  • 1
    Hi.. Welcome to SO, please include the code you might have to get the desired output. – sushanth Aug 09 '21 at 14:45
  • Does this answer your question? [How do I merge two dictionaries in a single expression (taking union of dictionaries)?](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona) – amirouche Aug 15 '21 at 09:49

3 Answers3

0
>>> d1 = { "Name": " John Doe", "Gender": "Male", "Phone": "01 9672 0321", "Occupation": "Engineer",
}
>>> d2 = { "First_Name": "Name", "Last_Name": "Name", "Gender": "Gender", "Phone": "Phone", "Occupation": "Occupation", }
>>> {k: d1[v] for k, v in d2.items()}
{'First_Name': ' John Doe', 'Last_Name': ' John Doe', 'Gender': 'Male', 'Phone': '01 9672 0321', 'Occupation': 'Engineer'}
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

Since your data is a little weird, some hard coding must be done (you have 'First_Name' in the second dictionary but want 'FirstName', etc... )

John Doe have a space at the beginning (I suppose it is an error...)

This code gives exactly what you want :

data1 = { "Name": "John Doe", "Gender": "Male", "Phone": "01 9672 0321", "Occupation": "Engineer",}

data2 = { "First_Name": "Name", "Last_Name": "Name", "Gender": "Gender", "Phone": "Phone", "Occupation": "Occupation", }

data3 = {}
for key in data2.keys():
    if key == 'First_Name':
        data3['FirstName'] = data1[data2[key]].split(' ')[0]
    elif key == 'Last_Name':    
        data3['LastName'] = data1[data2[key]].split(' ')[1]
    else:
        data3[key] = data1[key]
coyote
  • 194
  • 13
0

Some fix for code by coyote

for key in b.keys():
    if key == 'First_Name':
        c['FirstName'] = a[b[key]].split(' ')[1]
    elif key == 'Last_Name':
        c['LastName'] = a[b[key]].split(' ')[2]
    else:
        c[key] = a[key]