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

Create a dictionary based on a function and a list of strings

I have a list of strings, lostrings, and a function, splitter, which splits a string.

lostrings = 
    ['308 921 q53 C13 0000000200',
     '300 920 q51 C13 000000199',
     '318 921 q53 C12 0000000199']

def slitter(s: str) -> list:
    value1 = s[:3]
    value2 = s[4:7]
    value3 = s[9:12]
    value4 = s[14:17]
    value5 = s[25:]
    return [value1, value2, value3, value4, value5] 

Example: splitter(lostrings[0]) will output ['308', '921', 'q53', 'C13', '200'].

What I am trying to do is to create a key-value dictionary where keys are 'value1, 'value2', 'value3', 'value4', 'value5' and values are lists. Desired output is as follows:

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

{'value1': ['308', '300', '318'],
 'value2': ['912', '920', '921'],
 'value3': ['q53', 'q51', 'q53'],
 'value4': ['C13', 'C13', 'C12'],
 'value5': ['200', '199', '199']}

I tried the following:
1.

dict(zip(['value1', 'value2', 'value3', 'value4', 'value5'], [splitter[lostrings[row]] for row in range(len(lostrings))]))

This does not give the correct output. I am not sure how to create a dictionary of 'str':list out of a list of strings based on a function.

>Solution :

You can map the list of strings to the splitter function, transpose the output so that the lists align with the keys, which you can then zip together to construct a dict:

dict(
    zip(
        ['value1', 'value2', 'value3', 'value4', 'value5'],
        map(
            list,
            zip(*map(splitter, lostrings))
        )
    )
)

Demo: https://replit.com/@blhsing/OutstandingWeakGnudebugger#main.py

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