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

Time:11-05

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:

 [{'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
 

CodePudding user response:

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
  • Related