Home > Blockchain >  Convert list values which contain integers and strings to string after flattening a dictionary
Convert list values which contain integers and strings to string after flattening a dictionary

Time:12-20

I want to convert list values that contain integers and strings to string after flattening. List that contains dictionary should be flattened

Dictionary I have:

{
    "main_key": [
        {
            "key1": "val1",
            "key2": 0,
            "key3": [2,72,140],
            "key4": ["val2","val3","val4"]
        }
    ]
}

This post helped me very well, but it doesn't convert list value to string. I am using this code:

def flatten(input_dict, separator='/', prefix=''):
    output_dict = {}
    for key, value in input_dict.items():
        if isinstance(value, dict) and value:
            deeper = flatten(value, separator, prefix key separator)
            output_dict.update({key2: val2 for key2, val2 in deeper.items()})
        elif isinstance(value, list) and value:
            for sublist in value:
                if isinstance(sublist, dict) and sublist:
                    deeper = flatten(sublist, separator, prefix key separator)
                    output_dict.update({key2: val2 for key2, val2 in deeper.items()})
                elif isinstance(sublist, list):
                    output_dict[sublist] = ', '.join([str(ele) for ele in input_dict[sublist]])
                else:
                    output_dict[prefix key] = value
        else:
            output_dict[prefix key] = value
    return output_dict

I get:

{'main_key/key1': 'val1',
 'main_key/key2': 0,
 'main_key/key3': [2, 72, 140],
 'main_key/key4': ['val2', 'val3', 'val4']}

I expect:

{'main_key/key1': 'val1',
 'main_key/key2': 0,
 'main_key/key3': '2, 72, 140',
 'main_key/key4': 'val2, val3, val4'}

CodePudding user response:

This happens because inside the if isinstance(value, list) block, you check the type of each element of value and if those elements are not a list or dict, you do:

output_dict[prefix key] = value

This sets the output dict to value, which is a list.

As a hacky fix, do

output_dict[prefix key] = ", ".join(str(v) for v in value)

Ideally you should be doing this outside the for sublist in value loop. I suspect you don't need that loop anyway and can instead just check the type of the first element (if you assume that all elements of a list have the same type)

  • Related