Pandas Series: to_dict() function
Series-to_dict() function
The to_dict() function is used to convert Series to {label -> value} dict or dict-like object.
Syntax:
Series.to_dict(self, into=<class 'dict'>)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
into | The collections.abc.Mapping subclass to use as the return object. Can be the actual class or an empty instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized. | class, default dict | Required |
Returns: collections.abc.Mapping
Key-value representation of Series.
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4, 5])
s.to_dict()
Output:
{0: 2, 1: 3, 2: 4, 3: 5}
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4, 5])
from collections import OrderedDict, defaultdict
s.to_dict(OrderedDict)
Output:
OrderedDict([(0, 2), (1, 3), (2, 4), (3, 5)])
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4, 5])
from collections import OrderedDict, defaultdict
dd = defaultdict(list)
s.to_dict(dd)
Output:
defaultdict(list, {0: 2, 1: 3, 2: 4, 3: 5})
Previous: Series-to_csv() function
Next: Series-to_excel() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-to_dict.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics