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

Get max length of value inside a list which contains other lists

I got a list with keys and other lists. I want to create a function that checks the list for the longest value(string). It should give me back the longest string as number. I found nothing useful on the internet. only the strings with the key (value) need to be checked.
Output : It should count each character of the longest value(string).

Hope you can help me.

List:

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

 [{'name': 'title', 'value': 'titel{TM} D3', 'is_on_label': 1},
 {'name': 'DK in', 'value': '24V max 2.5A', 'is_on_label': 1,
 'id_configuration': 79,

 'options': [{'value': '30V max 3A', 'id_configuration_v': '1668'},
             {'value': 'none', 'id_configuration_v': '1696'}]}]

function:

def checkLenFromConfigs(self, configs):
   max_lenght = max(map(len, configs))
   return max_lenght
 

>Solution :

You could recursively search for all values in your data structure:

data = [{
        "name": "title",
        "value": "titel{TM} D3",
        "is_on_label": 1
    },
    [{
        "name": "title",
        "value": "titel{TM} D3",
        "is_on_label": 1,
        "sub_options": [
            {
                "value": "30V max 3A",
                "id_configuration_v": "1668"
            },
            {
                "value": "none none none none",
                "id_configuration_v": "1696"
            }
        ]
    }], 
    {
        "name": "DK in",
        "value": "24V max 2.5A",
        "is_on_label": 1,
        "id_configuration": 79,
        "options": [{
                "value": "30V max 3A",
                "id_configuration_v": "1668"
            },
            {
                "value": "none",
                "id_configuration_v": "1696"
            }
        ]
    }
]



def recur(data, count):
    if isinstance(data, list):
        for item in data:
            count = recur(item, count)
    elif isinstance(data, dict):
        for k, v in data.items():
            if k == 'value':
                count.append(len(v))
            else:
                count = recur(v, count)
    return count

result = recur(data, [])
print(max(result))

Out:

19
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