如何将嵌套列表转换为字典列表?(支持任意数量子列表)
Solution
To convert your nested list into the desired list of dictionaries (and handle any number of sublists), you can use Python's built-in zip() function along with list comprehensions. Here's a concise, flexible approach:
Code Example
temp = [ ['header1', '4', '8', '16', '32', '64', '128', '256', '512', '243,6'], ['media_range', '1,200', '2,400', '4,800', '4,800', '6,200', '38,400', '76,800', '153,600', '160,000'], ['speed', '300', '600', '1,200', '2,000', '2,000', '2,000', '2,000', '2,000', '2,000'] ] # Extract the header keys from each sublist headers = [sublist[0] for sublist in temp] # Zip together all the data values (skipping the header in each sublist) data_rows = zip(*[sublist[1:] for sublist in temp]) # Generate the list of dictionaries output = [dict(zip(headers, row)) for row in data_rows] # Print the result to verify for item in output: print(item)
How It Works
- Extract Headers: We first grab the first element of each sublist to use as the keys for our dictionaries. This works no matter how many sublists you have.
- Zip Data Rows: Using
zip(*[sublist[1:]...]), we transpose the data—turning columns into rows. Each "row" here is a tuple of corresponding values from each sublist (e.g.,('4', '1,200', '300')for the first entry). - Build Dictionaries: For each row of values, we pair them with the headers using
dict(zip(headers, row)), creating a dictionary for each set of corresponding entries.
Example Output
The first few entries of output will look exactly like you expected:
{'header1': '4', 'media_range': '1,200', 'speed': '300'} {'header1': '8', 'media_range': '2,400', 'speed': '600'} {'header1': '16', 'media_range': '4,800', 'speed': '1,200'} ...
Notes
- This approach handles any number of sublists automatically—just add more sublists to
tempand the code will adapt (as long as all sublists have the same length after the header element). - If sublists have mismatched lengths,
zip()will stop at the shortest one. For strict handling, you could useitertools.zip_longest, but that's usually unnecessary for structured data like this.
内容的提问来源于stack exchange,提问作者goku
相关产品推荐
相关产品推荐

