0

I have dates in string form in list of lists in a dictionary. I wrote a function to convert date strings to datetimes. I would like to convert all string dates in my dictionary to date times. My code only converts the first sublist in each table and it has no way of getting the others. What's the best way to do this?

import datetime

def parse_date(datestamp):
      try:
          return datetime.datetime.strptime(str(datestamp)[:10], '%Y-%m-%d')
      except ValueError:
          pass

My_Dict = {
    'Value1': {'Dates' : [['2014-10-14', 10, '2014-10-13', '2014-11-03'], ['2014-10-14', '2014-10-14', '2014-11-03']]},
    'Value2': {'Dates' : [['2014-10-14', '2014-10-13', '2014-11-03'], ['2014-10-14', '2014-10-14', '2014-11-03']]},
    }

for tbl in My_Dict:
    print [parse_date(x) for x in My_Dict[tbl]['Dates'][0]]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user2242044
  • 8,803
  • 25
  • 97
  • 164

2 Answers2

1

It's a matter of expanding out your nested lists correctly:

for key in My_Dict:
    for data in My_Dict[key]["Dates"]:
        for date in data:
            print date, parse_date(date)

Gives:

2014-10-14 2014-10-14 00:00:00
2014-10-13 2014-10-13 00:00:00
2014-11-03 2014-11-03 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-11-03 2014-11-03 00:00:00
2014-10-14 2014-10-14 00:00:00
10 None
2014-10-13 2014-10-13 00:00:00
2014-11-03 2014-11-03 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-10-14 2014-10-14 00:00:00
2014-11-03 2014-11-03 00:00:00

To put this into a single flat list you could do:

print [parse_date(date) for key in My_Dict for data in My_Dict[key]["Dates"] for date in data]

but I think the three loops are much easier to read!

Hooked
  • 84,485
  • 43
  • 192
  • 261
1

Nest your list comprehension as

print [[parse_date(x) for x in i] for i in My_Dict[tbl]['Dates']]

But if you want a flat list, then you can try as Hooke mentioned, that is

print [parse_date(date) for key in My_Dict for data in My_Dict[key]["Dates"] for date in data]
Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • Sorry, ignore what I said about removing the brackets, I was too hasty. The proper way would probably be with itertools to do it in one line. – Hooked Jan 19 '15 at 19:20
  • @Hooked Yep. `itertools` is the key. Isn't it cool that Python has all the functions that you want already as libraries? – Bhargav Rao Jan 19 '15 at 19:23
  • You can do it without itertools, you just have to reverse the order. `print [parse_date(date) for key in My_Dict for data in My_Dict[key]["Dates"] for date in data]`. See http://stackoverflow.com/a/11264751/249341 – Hooked Jan 19 '15 at 19:24