Convert values to DataFrame
, replace missing values (added for missing combinations) and last convert to dictionary by DataFrame.to_dict
:
d = [{"city": "a", "country": "b", "house": "12"},
{"city": "z", "country": "d", "floorlevel": "3"}]
out = pd.DataFrame(d).fillna('missing').to_dict(orient='list')
print(out)
{'city': ['a', 'z'],
'country': ['b', 'd'],
'house': ['12', 'missing'],
'floorlevel': ['missing', '3']}
Pure python solution:
d = [{"city": "a", "country": "b", "house": "12"},
{"city": "z", "country": "d", "floorlevel": "3"}]
#inspired by https://stackoverflow.com/a/2366681/2901002
out = {k:[d1.get(k, 'missing') for d1 in d] for k in {k for d1 in d for k in d1}}
print (out)
{'house': ['12', 'missing'],
'country': ['b', 'd'],
'floorlevel': ['missing', '3'],
'city': ['a', 'z']}