xingyuan jiang
xingyuan jiang

Reputation: 153

pandas -- How to get Series to dict

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

Upvotes: 4

Views: 5141

Answers (1)

jezrael
jezrael

Reputation: 863801

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()]

Upvotes: 7

Related Questions