When should I create a dataframe using a dictionary or a list?


#1

Question

When should I create a Pandas dataframe using a dictionary or a list?

Answer

You can create Pandas dataframes using either a dictionary or a list of lists, but depending on several factors, using one can be preferred over the other.

Using dictionaries can be much faster, since you can just include the column names as the keys, and include the values of the column as a list for the keys. However, a disadvantage of using a dictionary is that the columns will not preserve the order that you entered them, and will default to alphabetical ordering instead. This is important to keep in mind especially if the column order is important.

Using a list of lists allows you to enter each row of data one at a time as a separate list, but it may take longer than using a dictionary, since column names must be added as a separate list after the rows are added. However, a list of lists allows you to order the column names specifically, which can be very important.