如何将Python字典原键转换为对应值并重构字典结构
Solution: Add Original Turtle Names to Your Dictionary Entries
Got it, let's fix this up so your dictionary includes the original turtle names while keeping the turtle_1/turtle_2 key format you want. Here's a straightforward modification to your existing loop that preserves the original names and keeps your data consistent for pandas:
Step 1: Modify Your Loop to Include Original Names
We'll adjust your existing code to insert the original turtle name into the info list (matching your existing KEY: Value format):
data_dict = {'Aesop': ['AGE: 7 Years Old', 'WEIGHT: 6 lbs', 'SEX: Female', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie'], 'Caesar': ['AGE: 2 Years Old', 'WEIGHT: 4 lbs', 'SEX: Male', 'BREED: Greek Tortoise', 'SOURCE: hatched in house'], 'Sulla': ['AGE: 1 Year Old', 'WEIGHT: 1 lb', 'SEX: Male', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie']} name_num = 1 for old_name in list(data_dict.keys()): # Pull the existing info list for the turtle turtle_info = data_dict.pop(old_name) # Add the original name to the list (we'll insert at the start for clarity) turtle_info.insert(0, f'NAME: {old_name}') # Assign the updated list to the new turtle_* key data_dict[f"turtle_{name_num}"] = turtle_info name_num += 1
What This Does
- We use
list(data_dict.keys())to avoid errors from modifying the dictionary while iterating over it. - The
insert(0, ...)adds the name as the first entry in the info list, but you can swap it forappend(...)if you prefer the name at the end. - Your final dictionary will look like this:
{ 'turtle_1': ['NAME: Aesop', 'AGE: 7 Years Old', 'WEIGHT: 6 lbs', 'SEX: Female', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie'], 'turtle_2': ['NAME: Caesar', 'AGE: 2 Years Old', 'WEIGHT: 4 lbs', 'SEX: Male', 'BREED: Greek Tortoise', 'SOURCE: hatched in house'], 'turtle_3': ['NAME: Sulla', 'AGE: 1 Year Old', 'WEIGHT: 1 lb', 'SEX: Male', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie'] }
Bonus: Convert to Key-Value Dictionaries for Easier Pandas Use
If you want to make the data even more pandas-friendly (turning each list into a proper key-value dict), add this helper function:
def convert_list_to_dict(info_list): info_dict = {} for item in info_list: # Split only on the first colon-space to handle values with colons (if any) key, value = item.split(': ', 1) # Optional: Convert keys to lowercase for consistency in your DataFrame info_dict[key.lower()] = value return info_dict # Update the loop to use this function name_num = 1 clean_data_dict = {} for old_name in list(data_dict.keys()): turtle_info = data_dict.pop(old_name) turtle_info.insert(0, f'NAME: {old_name}') clean_data_dict[f"turtle_{name_num}"] = convert_list_to_dict(turtle_info) name_num += 1
Now your data is structured as nested dictionaries, which you can turn into a pandas DataFrame in one line:
import pandas as pd turtle_df = pd.DataFrame.from_dict(clean_data_dict, orient='index')
内容的提问来源于stack exchange,提问作者Arafat Khan
相关产品推荐
相关产品推荐

