Python3.6(Django):如何将列表字典转实例字典用于API与图表展示
Got it, let's break down how to solve this problem cleanly with Python 3.6 (perfect for your Django use case). The core idea is to map each index position across all your lists into a single instance dictionary, then package those instances into the final structure you need for your API and charts.
Step 1: Understand the Data Mapping
Your source data has keys ending with _list, each holding values that correspond to the same instance at the same index. We need to:
- Extract elements at each index from every list
- Rename the keys by stripping off the
_listsuffix (or use a custom mapping if needed) - Package each set of indexed elements into an
instanceNentry
Step 2: Code Implementation
First, let's start with your sample source data:
source_data = { 'sensor_state_list': ['in_service', 'in_service'], 'rx_sensor_delta_list': [0, 321144], 'tx_sensor_delta_list': [0, 321144], 'discard_sensor_delta_list': [0, 321144], 'time_list': ['2019-03-08 10:30:11.049860+00:00', '2019-03-08 12:47:16.722241+00:00'] }
Option 1: Generic Approach (Assuming All Keys End with _list)
This works if all your source keys follow the X_list pattern, so we can automatically derive the target key names:
# First, validate all lists have the same length to avoid mismatched data list_lengths = [len(values) for values in source_data.values()] if not all(length == list_lengths[0] for length in list_lengths): raise ValueError("All lists in the source data must have identical lengths") # Generate the instance collection result = { f'instance{idx + 1}': { # Strip '_list' from the source key to get the target key key[:-5]: source_data[key][idx] for key in source_data } for idx in range(list_lengths[0]) }
Option 2: Custom Key Mapping (More Flexible)
If your source keys don't all follow the _list pattern, or you want explicit control over target key names, use a custom mapping:
# Define how source keys map to target keys key_mapping = { 'sensor_state_list': 'sensor_state', 'rx_sensor_delta_list': 'rx_sensor_delta', 'tx_sensor_delta_list': 'tx_sensor_delta', 'discard_sensor_delta_list': 'discard_sensor_delta', 'time_list': 'time' } # Validate list lengths (same as before) list_lengths = [len(values) for values in source_data.values()] if not all(length == list_lengths[0] for length in list_lengths): raise ValueError("All lists in the source data must have identical lengths") # Generate the instance collection result = {} for idx in range(list_lengths[0]): instance_key = f'instance{idx + 1}' result[instance_key] = { target_key: source_data[source_key][idx] for source_key, target_key in key_mapping.items() }
Step 3: Verify the Result
Running either option with your sample data will produce exactly the structure you need:
{ 'instance1': { 'sensor_state': 'in_service', 'rx_sensor_delta': 0, 'tx_sensor_delta': 0, 'discard_sensor_delta': 0, 'time': '2019-03-08 10:30:11.049860+00:00' }, 'instance2': { 'sensor_state': 'in_service', 'rx_sensor_delta': 321144, 'tx_sensor_delta': 321144, 'discard_sensor_delta': 321144, 'time': '2019-03-08 12:47:16.722241+00:00' } }
Key Notes for Django Use
- This code is lightweight and can be integrated directly into your Django view or serializer.
- The length validation step is crucial to prevent runtime errors if your前置函数 returns mismatched list lengths.
- The f-string syntax (
f'instance{idx + 1}') is fully supported in Python 3.6+, which aligns with your environment.
内容的提问来源于stack exchange,提问作者Death Machine

