I’m trying to convert a list of lists with strings like:
JavaScript
x
6
1
[
2
["amenity=language_school"],
3
["amenity=sport_school,place=rural", "amenity=sport_school,place=urban"],
4
["amenity=middle_school,place=city", "amenity=high_school,place=city"]
5
]
6
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:
JavaScript
1
6
1
[
2
{"amenity":"language_school"},
3
{"amenity":"sport_school", "place":["rural","urban"]},
4
{"amenity":["middle_school", "high_school"], "place":"city"}
5
]
6
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
JavaScript
1
17
17
1
output_list = []
2
for each_row in [
3
["amenity=language_school"],
4
["amenity=sport_school,place=rural", "amenity=sport_school,place=urban"],
5
["amenity=middle_school,place=city", "amenity=high_school,place=city"]
6
]:
7
output_list.append(dict())
8
for each_element in each_row:
9
for each_def in each_element.split(','):
10
key, value = each_def.split('=')
11
if key in output_list[-1]:
12
if value not in output_list[-1][key]:
13
output_list[-1][key].append(value)
14
else:
15
output_list[-1][key] = [value]
16
print(output_list)
17
The output:
JavaScript
1
2
1
[{'amenity': ['language_school']}, {'amenity': ['sport_school'], 'place': ['rural', 'urban']}, {'amenity': ['middle_school', 'high_school'], 'place': ['city']}]
2
And this is an alternative way with the same output:
JavaScript
1
15
15
1
output_list = []
2
for each_row in [
3
["amenity=language_school"],
4
["amenity=sport_school,place=rural", "amenity=sport_school,place=urban"],
5
["amenity=middle_school,place=city", "amenity=high_school,place=city"]
6
]:
7
output_list.append(dict())
8
for each_element in each_row:
9
for each_def in each_element.split(','):
10
key, value = each_def.split('=')
11
content = output_list[-1].get(key, [])
12
output_list[-1][key] = content + ([value] if value not in content else [])
13
print(output_list)
14
15