Home > Enterprise >  Convert a dataframe to dictionary
Convert a dataframe to dictionary

Time:12-02

I have this data like this

technologies = [
            ("a","2","3"),
            ("4","5","6"),
            ("7","8","9")
            ]
df = pd.DataFrame(technologies,columns = ['C1','C2','C3'])
print(df)

and i convert it to this df

  C1 C2 C3
0  a  2  3
1  4  5  6
2  7  8  9

then i convert DataFrame to Dictionary of Records

df2 = df.to_dict('records')
print(df2)

and i got this

[{'C1': 'a', 'C2': '2', 'C3': '3'}, {'C1': '4', 'C2': '5', 'C3': '6'}, {'C1': '7', 'C2': '8', 'C3': '9'}]

Now i want my output would be like this

[{'C1': 'a',
  'C2': '2', 
  'C3': '3'}, 
 {'C1': '4', 
  'C2': '5', 
  'C3': '6'}, 
 {'C1': '7', 
  'C2': '8', 
  'C3': '9'}]

Is there anychance to get my expect output? i'm just the beginner, please help me to find out

CodePudding user response:

You can use pprint.pprint() for that. Something like this:

>>> from pprint import pprint
>>> d = [{'C1': 'a', 'C2': '2', 'C3': '3'}, {'C1': '4', 'C2': '5', 'C3': '6'}, {'C1': '7', 'C2': '8', 'C3': '9'}]
>>> pprint(d, width=10)
[{'C1': 'a',
  'C2': '2',
  'C3': '3'},
 {'C1': '4',
  'C2': '5',
  'C3': '6'},
 {'C1': '7',
  'C2': '8',
  'C3': '9'}]
>>> 

And with the default width, the output is the following:

>>> pprint(d)
[{'C1': 'a', 'C2': '2', 'C3': '3'},
 {'C1': '4', 'C2': '5', 'C3': '6'},
 {'C1': '7', 'C2': '8', 'C3': '9'}]
>>> 
  • Related