Search code examples
pythonjsonstrip

missing few lines to print


below is my code:

output_dict = {}
for item in show_vs:
    splitted = item.split(": ")
    if len(splitted) <= 1:
        continue
    output_dict[
        splitted[0].strip()
    ] = splitted[1].strip()
jsn = json.dumps(output_dict, indent=4)
print(jsn)

below is my data, the code prints only last 10 keys and its values in json format but it is not printing the first 20 keys and its values at all, any suggestions?

show_vs = [
    'VSID:            0   ',
    'VRID:            0   ',
    'Type:            VSX Gateway',
    'Name:            chckpt-fw1a',
    'Security Policy: VS-policy',
    'Installed at:    12Jan2023 21:57:15',
    'SIC Status:      Trust',
    'Connections number: 52',
    'Connections peak: 152',
    'Connections limit:  14900',

    'VSID:            1   ',
    'VRID:            1   ',
    'Type:            VSX Gateway',
    'Name:            chckpt-fw1a',
    'Security Policy: VS-policy',
    'Installed at:    12Jan2023 21:57:15',
    'SIC Status:      Trust',
    'Connections number: 52',
    'Connections peak: 152',
    'Connections limit:  14900',

    'VSID:            2   ',
    'VRID:            2   ',
    'Type:            VSX Gateway',
    'Name:            chckpt-fw1a',
    'Security Policy: VS-policy',
    'Installed at:    12Jan2023 21:57:15',
    'SIC Status:      Trust',
    'Connections number: 52',
    'Connections peak: 152',
    'Connections limit:  14900',
]

Solution

  • You can't have duplicate keys in a dictionary, so you need to create a list of dictionaries, one for each VSID.

    output_dicts = []
    
    for  item in show_vs:
        splitted = item.split(": ")
        if len(splitted) <= 1:
            continue
        key, value = map(str.strip, splitted[:2])
        if key == 'VSID':
            new_dict = {}
            output_dicts.append(new_dict)
        new_dict[key] = value
    
    jsn = json.dumps(output_dicts, indent=4)
    print(jsn)