0

I have a python dictionary,dict1 where keys are integer & values are string. I want to create a pandas data frame with this dictionary.Can you please suggest me how to do that in python 3.X?

I used following code

df_i=pd.DataFrame(dict1,columns=['num_int','num_str'])

But got error message

ValueError: If using all scalar values, you must pass an index

I also tried the steps mentioned in here but I got output like

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...

for all the rows

My sample dictionary looks like

1:  '031155233',
2:  '031420399',
3:  '031442593',
4:  '032952341',
5:  '033141410',
6:  '033404365',
7:  '033423523',
8:  '033461055',
9:  '012025663',
10: '012322156',
11: '021422395',
12: '036145459',
13: '035910162',
14: '042144641',
15: '042525232',
16: '040535923',
17: '042523604',
18: '029090230',
19: '012402315',
Christina Hughes
  • 357
  • 3
  • 5
  • 11
  • Your sample dictionary doesn't look right, there is a unmatched quotation mark on each line. You can just paste the output of `print(dict1)`. – nnnmmm Feb 08 '18 at 13:04

1 Answers1

0

I think you should just add orient = 'index' when calling pd.DataFrame.from_dict()

my_dict = {1:  '031155233',
2:  '031420399',
3:  '031442593'}

>>> pd.DataFrame.from_dict(my_dict, orient='index')

    0
1   031155233
2   031420399
3   031442593

And if you need to pass in the column names you mention, here's a way :

df = pd.DataFrame.from_dict(my_dict, orient='index').reset_index()
df.columns = ['num_int','num_str']

>>> print(df)
    num_int num_str
0   1   031155233
1   2   031420399
2   3   031442593
arnaud
  • 3,293
  • 1
  • 10
  • 27
  • Thank yoy @Arnaud I will check this & will let you know.I missed to put one more thing.This dictionary contains around 500,000 elements.Is your method will create any problem for that(Like more time to process)? – Christina Hughes Feb 08 '18 at 13:29
  • I don't think there would be computation time issues as that method was explicitly designed to integrate dicts into DataFrames. But, try and tell us :-) – arnaud Feb 08 '18 at 13:33