如何在Python中实现指定的字典字段映射并拆分姓名值?
Hey there! Let's walk through how to get your desired output step by step. Since you're new to Python, I'll keep things simple and explain each part clearly.
First, let's recap what we need to do:
- Split the "Name" field from the first dictionary into separate first and last names
- Map the other fields directly using the second dictionary's mapping
- Adjust the key names from underscore format (like "First_Name") to camelCase (like "FirstName")
Step 1: Initialize your input dictionaries
First, let's write down the two dictionaries you provided:
first = { "Name": " John Doe", "Gender": "Male", "Phone": "01 9672 0321", "Occupation": "Engineer" } second = { "First_Name": "Name", "Last_Name": "Name", "Gender": "Gender", "Phone": "Phone", "Occupation": "Occupation" }
Step 2: Process the full name
The "Name" field has a leading space, so first we'll strip that extra whitespace, then split it into first and last name parts:
# Remove leading/trailing spaces and split into a list of name parts name_parts = first["Name"].strip().split() # The first element is the first name, second is last name first_name = name_parts[0] last_name = name_parts[1]
Step 3: Build the output dictionary
We can create the output in two ways: a simple manual approach (great for small dicts) or a dynamic approach (better if your dicts might grow later).
Option 1: Manual approach (easy to follow)
This is straightforward for your specific case:
output = { "FirstName": first_name, "LastName": last_name, "Gender": first[second["Gender"]], # Maps directly from first["Gender"] "Phone": first[second["Phone"]], # Maps directly from first["Phone"] "Occupation": first[second["Occupation"]] # Maps directly from first["Occupation"] }
Option 2: Dynamic approach (scalable)
If you think your dictionaries might have more fields later, this loop will handle all keys automatically:
output = {} for key, mapped_key in second.items(): # Convert keys like "First_Name" to "FirstName" by removing the underscore new_key = key.replace("_", "") if key == "First_Name": # Use the first part of the split name output[new_key] = name_parts[0] elif key == "Last_Name": # Use the second part of the split name output[new_key] = name_parts[1] else: # For other fields, use the mapped value from the first dictionary output[new_key] = first[mapped_key]
Step 4: Check the result
Finally, print the output to see if it matches what you want:
print(output)
This will give you exactly the desired result:
{"FirstName": "John", "LastName": "Doe", "Gender": "Male", "Phone": "01 9672 0321", "Occupation": "Engineer"}
A quick note: This assumes the "Name" field always has exactly two parts (first and last). If there's a chance of middle names, you might need to adjust the splitting logic, but for your current case, this works perfectly.
内容的提问来源于stack exchange,提问作者jia

