Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I have a Python dictionary like the following:


U'2012-06-08': 388, u'2012-06-09': 388, u'2012-06-10': 388, u'2012-06-11': 389, u'2012-06-12': 389, u'2012-06-13': 389, u'2012-06-14': 389, u'2012-06-15': 389, u'2012-06-16': 389, u'2012-06-17': 389, u'2012-06-18': 390, u'2012-06-19': 390, u'2012-06-20': 390, u'2012-06-21': 390, u'2012-06-22': 390, u'2012-06-23': 390, u'2012-06-24': 390, u'2012-06-25': 391, u'2012-06-26': 391, u'2012-06-27': 391, u'2012-06-28': 391, u'2012-06-29': 391, u'2012-06-30': 391, u'2012-07-01': 391, u'2012-07-02': 392, u'2012-07-03': 392, u'2012-07-04': 392, u'2012-07-05': 392, u'2012-07-06': 392


The keys are Unicode dates and the values are integers. I would like to convert this into a pandas dataframe by having the dates and their corresponding values as two separate columns. Example: col1: Dates col2: DateValue (the dates are still Unicode and data values are still integers)

      Date          DateValue 

0     2012-07-01    391 

1     2012-07-02    392 

2     2012-07-03    392 

.     2012-07-04    392 

.     ...           ... 

.     ...           ...

Any help in this direction would be much appreciated. I am unable to find resources on the pandas docs to help me with this.

I know one solution might be to convert each key-value pair in this dict, into a dict so the entire structure becomes a dict of dicts, and then we can add each row individually to the dataframe. But I want to know if there is an easier way and a more direct way to do this.

So far I have tried converting the dict into a series object but this doesn't seem to maintain the relationship between the columns:

s = Series(my_dict,index=my_dict.keys())

1 Answer

0 votes
by (106k points)

When converting a dictionary into a pandas dataframe where you want the keys to be the columns of said dataframe and the values to be the row values, you can do simply put brackets around the dictionary like this:

new_dict = {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'} 



         key 1   key 2 key 3 

0       value 1 value 2  value 3

It's saved me some headaches so I hope it helps someone out there!

Browse Categories