'Reformatting python dictionaries within a List
I have a python List containing dictionaries like below
[{'mad phony': {'null': 49, 'valid': 10, 'invalid': 10}, 'base_url': 'https://madphony.org/'}, {'nashvilly': {'null': 18, 'valid': 5, 'invalid': 4}, 'base_url': 'https://www.nashvilly.org/'}]
I want this data to be formatted like
[{"org":"mad phony", "base_url": "https://madphony.org/", "pend_val":49, "val":20},
{"org":"nashvilly", "base_url": "https://www.nashvilly.org/", "pend_val":18, "val":9}]
Is there an efficient manner to reformat like this
Solution 1:[1]
This is likely not the most efficient way but it is clear and standard,
in_data = [{'mad phony': {'null': 49, 'valid': 10, 'invalid': 10}, 'base_url': 'https://madphony.org/'}, {'nashvilly': {'null': 18, 'valid': 5, 'invalid': 4}, 'base_url': 'https://www.nashvilly.org/'}]
out_data = []
for dict_i in in_data:
temp_dict = {}
# Process each dictionary in the list
for key, value in dict_i.items():
# Different processing for the URL part
if 'base_url' in key:
temp_dict[key] = value
else:
temp_dict['org'] = key
temp_dict['pend_val'] = value['null']
temp_dict['val'] = value['valid'] + value['invalid']
out_data.append(temp_dict)
The code iterates through the input list and using some assumptions on the structure of its elements constructs the output.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | atru |
