开发者

How do I use sorted dates in a list as keys for a dictionary in Python?

I have some Python code where I need to call upon a dictionary entry with a key that is a date.

    start = (date_objects[0])
    end = (date_objects[-1])
    print "The study's first trading day was", start, "and the last day was", end,"."
    print ""
    print histodict['2011-06-15']['Close']
    print histodict[start]['Open']

I have all the dates sorted and placed into a list named date_objects. The dates are also formatted as dates. When I try to print a variable containing a point on the list of dates everything is hunky-dory and I get a neat printout like YYYY-MM-DD instead of the date form of datetime.date(2010, 1, 4). Now what I need to do is get this nice, post-sorted, list to be able开发者_Go百科 to be used for keys in a dictionary. I have keys that are also in the form YYYY-MM-DD. Why is it that when I try to use a variable with a point on the list of date objects as the key value for my dictionary histodict it doesn't not work?


A date object is hashable. That's why you can use it as a dictionary key. But that doesn't mean a date object is hashed to the human-readable string representation you use (or see when you print the date object) because __hash__ and __str__ methods of date which do the hashing and converting to string are not necessarily the same.

You could try histodict[str(start)]['Open'] (i.e., convert the date variable to a string by using the __str__ method of date objects before using it as a key).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜