Thursday 7 September 2023

Convert Pandas Series to Dictionary

‘dict’ method takes a series object and return the dictionary. The resulting dictionary have series index values as key and corresponding values as dictionary values.

 

Example 1: With default numeric index

primes = [2, 3, 5, 7]
series = pd.Series(primes)
primes_dict = dict(series)

 

‘primes_dict’ contain below values.

{0: 2, 1: 3, 2: 5, 3: 7}

 

Example 2: With index labels.
index_labels = ['first_prime', 'second_prime', 'third_prime', 'fourth_prime']
series = pd.Series(primes, index_labels)
primes_dict = dict(series)

 

‘primes_dict’ contain the below data.

{'first_prime': 2, 'second_prime': 3, 'third_prime': 5, 'fourth_prime': 7}

 

convert_list_to_dictionary.py

import pandas as pd

primes = [2, 3, 5, 7]
series = pd.Series(primes)

print('Original Data : ')
print(series)

primes_dict = dict(series)
print('primes_dict : ', primes_dict)

index_labels = ['first_prime', 'second_prime', 'third_prime', 'fourth_prime']
series = pd.Series(primes, index_labels)

print('\nOriginal Data : ')
print(series)

primes_dict = dict(series)
print('primes_dict : ', primes_dict)

 

Output

Original Data : 
0    2
1    3
2    5
3    7
dtype: int64
primes_dict :  {0: 2, 1: 3, 2: 5, 3: 7}

Original Data : 
first_prime     2
second_prime    3
third_prime     5
fourth_prime    7
dtype: int64
primes_dict :  {'first_prime': 2, 'second_prime': 3, 'third_prime': 5, 'fourth_prime': 7}

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment