user106279 user106279 - 7 months ago 7
Python Question

Adding values to dictionary through loop using pandas dataframe

So I am trying to modify this dictionary that I converted using pandas. However I still get the error message that:

for key in dictionary:
TypeError: 'instancemethod' object is not iterable


i = pandas.date_range('20110101', '20151231')
df = pandas.DataFrame(dict(year = i.year, month = i.month, day = i.day))
time_format = pandas.to_datetime(df.year*10000 + df.month*100 + df.day, format='%Y%m%d')
times = (time_format.to_dict)

def adding_to_dict(dictionary):
for key in dictionary:
dictionary[key].append(list_of_random)
return dictionary

print adding_to_dict(times)


I did try to use a short dictionary to use the function but still with no luck. I am trying to add list/tuples of values to this new dictionary of timestamps. Any help would be greatly appreciated. Thanks for your time

Answer

if you try print(times) you'll see that it's not a dictionary. Also you're attempting to append to a dictionary, which is not how you add values to a dict. You just do dict[key] = value

Assuming you want your output to be {timestamp: values}, this should work.

import pandas
import datetime

i = pandas.date_range('20110101', '20151231')
df = pandas.DataFrame(dict(year=i.year, month=i.month, day=i.day))
time_format = pandas.to_datetime(df.year * 10000 + df.month * 100 + df.day, format='%Y%m%d')
times = dict(time_format)
output = {}
def adding_to_dict(dictionary):
    for key, value in dictionary.items():
        output[datetime.datetime.strftime(value, "%Y-%m-%d")] = 'whatever'

    return output


print adding_to_dict(times)

Output:

{'2013-09-08': 'whatever', '2014-01-30': 'whatever', '2012-12-03': 'whatever', '2014-03-21': 'whatever'}
Comments