Skip to content
Advertisement

Convert list of lists with strings into list of dictionaries

I’m trying to convert a list of lists with strings like:

[
 ["amenity=language_school"],
 ["amenity=sport_school,place=rural", "amenity=sport_school,place=urban"], 
 ["amenity=middle_school,place=city", "amenity=high_school,place=city"]
]

Some lists can have multiple string elements, and some of the string elements can have multiple key:values separated by a , like "amenity=high_school,place=city".

My goal is to get a list of dicts, in which the key of each dict could append in list several values from the same key. Like this:

[
 {"amenity":"language_school"},
 {"amenity":"sport_school", "place":["rural","urban"]}, 
 {"amenity":["middle_school", "high_school"], "place":"city"}
]

Advertisement

Answer

This code works for you. Just if you want any list with just one member to become converted to a simple String it needs to add one line code to it.

Good wishes

output_list = []
for each_row in [
 ["amenity=language_school"],
 ["amenity=sport_school,place=rural", "amenity=sport_school,place=urban"], 
 ["amenity=middle_school,place=city", "amenity=high_school,place=city"]
]:
    output_list.append(dict())
    for each_element in each_row:
        for each_def in each_element.split(','):
            key, value = each_def.split('=')
            if key in output_list[-1]:
                if value not in output_list[-1][key]:
                    output_list[-1][key].append(value)
            else:
                output_list[-1][key] = [value]
print(output_list)         

The output:

[{'amenity': ['language_school']}, {'amenity': ['sport_school'], 'place': ['rural', 'urban']}, {'amenity': ['middle_school', 'high_school'], 'place': ['city']}]

And this is an alternative way with the same output:

output_list = []
for each_row in [
 ["amenity=language_school"],
 ["amenity=sport_school,place=rural", "amenity=sport_school,place=urban"], 
 ["amenity=middle_school,place=city", "amenity=high_school,place=city"]
]:
    output_list.append(dict())
    for each_element in each_row:
        for each_def in each_element.split(','):
            key, value = each_def.split('=')
            content = output_list[-1].get(key, [])
            output_list[-1][key] =  content + ([value] if value not in content else [])
print(output_list)
            
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement