Hit enter after type your search item

3 Examples of Pandas Dict to Data Frames

How to convert a Python dictionary to data frame

In this tutorial, we will use Python dictionary and convert it into the Pandas data frame.

A data frame is the most commonly used object of Pandas – A popular Python library for data science and analysis.

The data frame object has class methods that can be used for converting a Python list, dictionary etc. to the data frame.

In this tutorial, we will show you examples of Data frame’s from_dict() method (pd.DataFrame.from_dict()) to convert dictionary to data frames.

Syntax of pd.DataFrame.from_dict()

classmethod DataFrame.from_dict(data, orient=’columns’, dtype=None, columns=None)

An example of a dict to a data frame

In the example below, we created a dictionary of telephone numbers that only contains Names and Phone numbers.

It contains three records for the demo only.

See the code and output below and we will explain how it worked.

Python Program:


Output:

pandas-dict-dataframe

In the program,

  • Imported the Pandas library
  • A dictionary is created with column headers and three rows
  • Data frame object is created and its from_dict method is used where we specified the dictionary name.
  • Finally, we displayed the data frame.

Using column names as index example

In the dictionary, we used the following column names (as you can see above):

  • Name
  • Phone No

If you want to use these as an index then you may use the orient parameter of the from_dict method.

The orient parameter has the following possible values:

  • columns (default)
  • index
  • tight

Above, we have seen the usage of columns which is the default. In that case, keys of the dictionary became columns of the DataFrame.

By using ‘index’ value, the result is as follows:


Output:

You can see, the keys of the dictionary became index.

Display DataFrame without index

Though, this is not straightforward to not show the index column (0,1,2…) by using from_dict method.

You may use other ways to hide the index column in the data frame.

In the following example, we will only display columns and rows provided in the dictionary –without row numbers:


Output:

we created a DateFrame based on a dict
  • Then we used to_string method with index=False to display the data frame without an index column.
This div height required for enabling the sticky sidebar