Home > Blockchain >  Converting dictionary values only to dataframe
Converting dictionary values only to dataframe

Time:02-03

I have a list of dictionaries that looks like this:

myDict = [{'Type': 'Type1',
          'Value': 'A'},
          {'Type': 'Type2',
           'Value': 'B'}
         ] 

And I'm trying to build a pandas dataframe that looks like this:

Type1   Type2
  A       B

This feels like it should be straight forward but I can't figure it out.

CodePudding user response:

Try modifying the dict before you use it:

modified_dict = dict(d.values() for d in myDict)
df = pd.DataFrame(modified_dict, index=[0])

Output:

>>> df
  Type1 Type2
0     A     B

CodePudding user response:

You have a list of dictionaries, where the values can be either columns or data. Based on the structure you provided, I made this solution using list comprehension.

df = pd.DataFrame([list(myDict[i].values())[1] for i in range(len(myDict))],
                  [list(myDict[i].values())[0] for i in range(len(myDict))]).T

The dataframe will look like the table below.

Type1 Type2
0 A B
  •  Tags:  
  • Related