Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding "sequential" information to python list using dictionaries

The problem

I would like to create a dictionary of dicts out of a flat list I have in order to add a "sequentiality" piece of information, but I am having some trouble finding a solution.

The list is something like

a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']

and I am shooting for a dict like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dictionary = {
    'Step_1': {
        'Q=123', 
        'W=456', 
        'E=789'
    },
    'Step_2': {
        'Q=753', 
        'W=159', 
        'E=888'
    }
}

I would like to end up with a function with an arbitrary number of Steps, in order to apply it to my dataset. Suppose that in the dataset there are lists like a with 1 <= n <6 Steps each.

My idea

Up to now, I came up with this:

nsteps = a.count("Q")
data = {}
for i in range(nsteps):
    stepi = {}
    for element in a:
            new = element.split("=")
            if new[0] not in stepi:
                stepi[new[0]] = new[1]
            else:
                pass
    data[f"Step_{i}"] = stepi

but it doesn’t work as intended: both steps in the final dictionary contain the data of Step_1.
Any idea on how to solve this?

>Solution :

One way would be:

a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']

indices = [i for i, v in enumerate(a) if 'Q' in v]

dictionary = {f'Step_{idx+1}': {k: v for k, v in [el.split('=') for el in a[s:e]]} 
              for idx, (s, e) in enumerate(zip(indices, indices[1:] + [len(a)]))}

print(dictionary)
{'Step_1': {'Q': '123', 'W': '456', 'E': '789'}, 
'Step_2': {'Q': '753', 'W': '159', 'E': '888'}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading