0

I have a dictionary where the keys are dates formatted '%m/%d/%y' and I want to parse this apart so I can graph the values by month. So the objective is just to transform the keys from m/d/y to just m and keep the same values in the dictionary.

months = dict.keys()
for i in months:
    i = dt.datetime.strptime(i[months],'%m/%d/%y').month

I get this error:

TypeError: string indices must be integers

Thanks for any suggestions.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Alicia
  • 121
  • 1
  • 12
  • Thanks for your nice comment, it was very helpful. I'm a beginner with python. I also tried just using months and that doesn't work either. – Alicia Feb 02 '18 at 00:42
  • You might as well just create a new dict and discard the previous ones, if you want to replace keys but keep the same values. – juanpa.arrivillaga Feb 02 '18 at 00:53
  • Can you update your question with an MCVE?https://stackoverflow.com/help/mcve – Chris Larson Feb 02 '18 at 00:53
  • That is, a minimal complete script, including dict? – Chris Larson Feb 02 '18 at 00:55
  • I think you might want to review the part of your book or tutorial that teaches for loops in more detail and try to understand what each value holds in detail. For example. I would recommend adding `print` calls with i and months in the loop to understand what the content of the variables is. – Azsgy Feb 02 '18 at 00:55
  • But the loop advice above is a good idea. – Chris Larson Feb 02 '18 at 00:56
  • Hi all, We did try using for loops, to no success. – Alicia Feb 02 '18 at 01:04

2 Answers2

4

Python isn't my expertise, but I know enough about programming to provide the following (and not be a snob about it):

from datetime import datetime

full_dates = ['1/1/17','2/1/17'] # best practice[1] is to use a list since this is an ordered sequence of items on an x-axis. Also, don't use dict since it's a reserved word in Python (it's used to create dictionaries using dict(...), which is the same as creating dict this way btw {...}[2])

months_only = []

for full_date in full_dates:
  months_only.append(datetime.strptime(month,'%m/%d/%y').month)

print(months_only) # outputs [1, 2]

[1] In Python, when to use a Dictionary, List or Set?

[2] https://developmentality.wordpress.com/2012/03/30/three-ways-of-creating-dictionaries-in-python/

Andres Narvaez
  • 516
  • 5
  • 11
0
months = dict.keys()
for i in months:
    i = dt.datetime.strptime(dict[i],'%m/%d/%y').month
Rakesh
  • 81,458
  • 17
  • 76
  • 113