简体   繁体   中英

Transforming a python dict into a list of lists

I inherited a confusing code that to form a table it uses a list of lists to primarily to get data from various sources, then to communicate with other APIs, it transforms into a dictionary which the key is composed from a letter and a number just like in a excel file, an example bellow:

[
    [elem1, elem2, elem3...],
    [item1, item2, item3...]
    [...]
]

transforms into

{
 "A1": elem1,
 "A2": elem2,
 "A3": elem3,
  ...
 "B1": item1,
 "B2": item2,
 ...
}

To make such transformation I've made the following piece of code where the items is the list of list and letters is a list containing the alphabet:

def create_dict(items, letters):
    data = {}
    for cidx, col in enumerate(items):
        for ridx, row in enumerate(col):
            data[letters[cidx] + str(ridx + 1)] = row

    return data

I know that there are better ways to do this, like using pandas and other things, but I'm trying to preserve the pattern and I'm having difficulties writing the code that makes the other way, which is to consume the dictionary and transform it into a list of lists so other intern APIs can insert more information in this table.

It sounds like you are happy-ish with your code to create a dictionary from the list of lists, and now you are looking for a way to run that process in reverse: go from a dictionary to a list of lists. One way to accomplish that is to cluster your dictionary keys by letter using the itertools groupby function.

Example:

import collections
import itertools

d = {
    "A1": "elem1",
    "A2": "elem2",
    "A3": "elem3",
    "B1": "item1",
    "B2": "item2",
}
od = dict(sorted(d.items()))

output_list = []

for _, group in itertools.groupby(od.items(), key=lambda item_tuple: item_tuple[0][0]):
    values = [
        one_value
        for _, one_value in group
    ]
    output_list.append(values)
    
print(output_list)

Output:

[['elem1', 'elem2', 'elem3'], ['item1', 'item2']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM