now I have this Series:
us 2
br 1
be 3
dtype: int64
so How get I can a list. as follows:
[ { "country": "us", "value": 2},
{ "country": "br", "value": 1},
{ "country": "be", "value": 3}
]
thanks
Create DataFrame
first and then use DataFrame.to_dict
:
print (s.rename_axis('country').reset_index(name='value').to_dict('records'))
[{'value': 2, 'country': 'us'}, {'value': 1, 'country': 'br'}, {'value': 3, 'country': 'be'}]
DataFrame
by constructor:
print (pd.DataFrame({'country':s.index, 'value':s.values}).to_dict('records'))
[{'value': 2, 'country': 'us'}, {'value': 1, 'country': 'br'}, {'value': 3, 'country': 'be'}]
Another solution with list comprehension
:
d = [dict(country=x[0], value=x[1]) for x in s.items()]
print (d)
[{'value': 2, 'country': 'us'}, {'value': 1, 'country': 'br'}, {'value': 3, 'country': 'be'}]
Similar solution from piRSquared deleted answer with Series.items
:
d = [dict(country=k, value=v) for k, v in s.items()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With