The problem statement
Given a list of dictionaries:
p = [
{'x': 1,
'a': [12, 14, 16],
'b': [13, 15],
'y': 8},
{'x': 2,
'a': [22, 24],
'b': [23, 25, 27],
'y': 9}
]
with some keys ('a' and 'b') in the form of lists, while others ('x' and 'y') as single values--
I'd like to create a rather flat dictionary, where the list key-values are segregated into separate keys 'a_1', 'a_2', ..., 'b_1', 'b_2', ..., etc. while keeping the single key-values as it is.
t = [
{'x': 1,
'a_1': 12,
'a_2': 14,
'a_3': 16,
'b_1': 13,
'b_2': 15,
'y': 8},
{'x': 2,
'a_1': 22,
'a_2': 24,
'b_1': 23,
'b_2': 25,
'b_3': 27,
'y': 9}
]
A partial solution
I was able to convert just one key 'a' having a list value to a dictionary with single values with the code:
q = [{'a_'+str(i+1): obj['a'][i]
for i in range(len(obj['a']))}
for obj in p]
print (q)
which gives an output looking like:
[
{'a_1': 12,
'a_2': 14,
'a_3': 16},
{'a_1': 22,
'a_2': 24}
]
but no idea how to do that for multiple keys... particularly to do this for those keys whose value is of type list, and simply keep the key-value otherwise... and finally merging all the key-values into one dictionary within the outer loop for obj in p.