Python嵌套字典迭代转换与REST API JSON角色名称提取问题
Hey there! Let's sort out that issue you're having with pulling the name fields from the nested roles dictionary.
What's Wrong With Your Current Code?
When you run for role in data2['roles'], Python is actually looping over the keys of the roles dictionary (those are the role ID strings like "1586230"). Your code then tries to call roles['name']—which fails because roles refers to the entire dictionary, not the individual role details, and you aren't using the role key to access the right value.
Correct Ways to Iterate Over the Nested Roles
Here are a few straightforward solutions depending on what you need:
1. Just Extract All Role Names
If you only need the name values from every role, use the .values() method to directly iterate over the role detail dictionaries:
import json with open('p1234.json') as file: data2 = json.load(file) # Loop through each role's details dictionary for role_details in data2['roles'].values(): print(role_details['name'])
This will output:
Systems Engineer Engineer- Software Engineer- SW
2. Get Both Role IDs and Names
If you want to keep the role ID paired with its name, use .items() to access both keys and values at once:
import json with open('p1234.json') as file: data2 = json.load(file) # Iterate over (role_id, role_details) pairs for role_id, role_details in data2['roles'].items(): print(f"Role ID: {role_id} | Name: {role_details['name']}")
Output:
Role ID: 1586230 | Name: Systems Engineer Role ID: 1586951 | Name: Engineer- Software Role ID: 1586932 | Name: Engineer- SW
3. Match IDs from results to Role Names
Since you also mentioned needing to extract IDs from the results list and get their corresponding role names, you can combine both steps like this:
import json with open('p1234.json') as file: data2 = json.load(file) # First, collect all IDs from the results section result_ids = [item['id'] for item in data2['results']] # Then fetch the matching name for each ID for role_id in result_ids: # Add a check to avoid KeyError if an ID doesn't exist in roles if role_id in data2['roles']: print(data2['roles'][role_id]['name'])
This will give you the names exactly for the IDs listed in results.
内容的提问来源于stack exchange,提问作者anish anil

