



Introduction

Many times, you will want to search through a dataframe so many times that both writing the search queries using dataframe rules and programmatically the search operation becomes redundant. In such cases, you will want to create a dictionary from a pandas dataframe. Now, if you wonder how, then I have the solution. Read on to explore more.

to_dict() method:

Possible is that you want to turn the rows into values while keeping one specific column as index. In such a case, you have to use the method as follows

df.set_index('id').to_dict()

zip and dict method:

You can use a simpler method and can get done in one line, if your goal is to turn one specific column into keys and one specific column into values, then you can use the zip and dict method. The details follows as below:

data_dict = dict(zip(data[key_column],data[value_column]))

Duplicate document problem:

This is a case when you have multiple values for each key. In that case, it will become a bit custom specific. One thing you can try to do is begin with a groupby and average or aggregate in some other fashion the multiple values occurring for each keys. But, if you seem to lose information in doing so, then you have to address the problem in other fashion. In short, you will open a empty dictionary. then you will populate each key with its associated values into the dictionary as a key-value pair. the related code can be as follows:

keys = list(df[key_column].unique())

my_dict = {}

#now populate

for key in keys: my_dict[key] = df[df[key_column] == key][value_column].tolist() #done

Conclusion:

These methods will lead to faster dictionary creation and therefore smoother and faster data analysis programs. Hope you enjoyed reading this! For further reading, go through the references: (1) 10 most important pandas functions (2) stackoverflow question which has inspired some of the codes here