Python技术问询:如何动态传递索引值并读取深度嵌套字典生成格式化输出
Got it, let's work through this problem together. You're dealing with a deeply nested dictionary from a response, and you need to dynamically handle indices while generating clean, formatted output—no hardcoding column positions, right? Here's a straightforward, flexible solution tailored to your structure:
Step 1: Extract the Header Row
First, we'll pull the column names from the first entry in the Rows list. This gives us our headers, so we don't have to rely on fixed indices later.
# Your original response (I filled in the truncated last row for completeness) response = { u'ResultSet': { u'Rows': [ {u'Data': [ {u'VarCharValue': u'Table_name'}, {u'VarCharValue': u'Validation_Scenario'}, {u'VarCharValue': u'No_of_Records'}, {u'VarCharValue': u'Result'} ]}, {u'Data': [ {u'VarCharValue': u'ABC'}, {u'VarCharValue': u'01_scenario2'}, {u'VarCharValue': u'100'}, {u'VarCharValue': u'FAIL'} ]}, {u'Data': [ {u'VarCharValue': u'ABC'}, {u'VarCharValue': u'02_scenario1'}, {u'VarCharValue': u'50'}, {u'VarCharValue': u'PASS'} ]} ] } } # Extract headers from the first row (no hardcoded indices here!) headers = [col[u'VarCharValue'] for col in response[u'ResultSet'][u'Rows'][0][u'Data']]
Step 2: Process Data Rows Dynamically
Next, we'll loop through the remaining rows (starting from index 1). For each row, we extract the values and map them directly to the headers. This way, we're using the header structure to define our data instead of hardcoding positions like [0] or [1].
# Process each data row into a dictionary of header: value pairs data_rows = [] for row in response[u'ResultSet'][u'Rows'][1:]: # Extract values by iterating through the Data list (dynamic index handling) values = [item[u'VarCharValue'] for item in row[u'Data']] # Make sure the row has the same number of columns as headers to avoid mismatches if len(values) == len(headers): data_rows.append(dict(zip(headers, values))) else: print(f"Warning: Skipping row with mismatched columns: {values}")
Step 3: Generate Clean Formatted Output
Now that we have a list of dictionaries (each representing a row with meaningful keys), we can generate output in whatever format you need. Here are two common options:
Option 1: Print a Formatted Table
This uses string formatting to align columns for readability:
# Calculate the width needed for each column (to align text) col_widths = [len(header) for header in headers] for row in data_rows: for idx, header in enumerate(headers): val = row[header] col_widths[idx] = max(col_widths[idx], len(val)) # Print the header row print(" | ".join(f"{header:<{col_widths[idx]}}" for idx, header in enumerate(headers))) # Print a separator line print("-+-".join("-" * width for width in col_widths)) # Print each data row for row in data_rows: print(" | ".join(f"{row[header]:<{col_widths[idx]}}" for idx, header in enumerate(headers)))
Output:
Table_name | Validation_Scenario | No_of_Records | Result -----------+---------------------+---------------+------- ABC | 01_scenario2 | 100 | FAIL ABC | 02_scenario1 | 50 | PASS
Option 2: Print Verbose Key-Value Pairs
If you prefer a more detailed view per record:
for record_num, row in enumerate(data_rows, 1): print(f"\nRecord {record_num}:") for key, value in row.items(): print(f" {key}: {value}")
Output:
Record 1: Table_name: ABC Validation_Scenario: 01_scenario2 No_of_Records: 100 Result: FAIL Record 2: Table_name: ABC Validation_Scenario: 02_scenario1 No_of_Records: 50 Result: PASS
Why This Works
- Dynamic Index Handling: We never hardcode indices for columns—we iterate through the
Datalist for each row, so this solution will adapt automatically if the number of columns changes later. - Flexibility: By converting rows to dictionaries first, you can easily switch output formats (like saving to CSV, JSON, or a database) without changing how you extract the data.
- Error Resilience: The check for matching column lengths prevents crashes if a row has missing or extra values.
内容的提问来源于stack exchange,提问作者Rajeev

