Home > OS >  Turn Multiple Separate Dictionaries Into Pandas Dataframe
Turn Multiple Separate Dictionaries Into Pandas Dataframe

Time:09-02

I am doing a rather large loop to pull out multiple key and value pairs which are then formed into multiple dictionaries. I want to turn these eventually into a dataframe. I am assuming I must first make a list out of them? Code looks so:

    data = {}
    ls_dict = []
    keys = [name]
    values = [number]
    for i in range(len(keys)):
        data[keys[i]] = values[i]
        ls_dict.append(data)
    print(ls_dict)

This loop is inside another larger loop. That is where the key and values are coming from.

When I run the code, I get the load of separate dictionaries like so:

 [{'name': number}]
 [{'name': number}]
 [{'name': number}]

But I was hoping to get them in a list like this:

 [{'name': number}, {'name': number}, {'name': number}]

The plan was then to return that list out of the function and turn it into a dataframe with column headings "User" and "User Number".

Any ideas first of all why it's not producing a list. And also, is there maybe a better way to make a dataframe out of the name and number im getting from my larger loop.

All help greatly appreciated.

CodePudding user response:

Try:

final_list = [{key: value} for key, value in zip(keys,values)] 

CodePudding user response:

It looks like both keys and values always have only a single element. That's why the given for loop does only one step. Could you maybe also show the outer loop?

A good way to turn this kind of data into dataframes might be to use the from_dict classmethod.

  • Related