简体   繁体   English

如何使用列表中的排序日期作为Python中字典的键?

[英]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. 我有一些Python代码,需要在其中用日期键来调用字典条目。

    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. 我将所有日期排序并放入名为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). 当我尝试在日期列表上打印包含点的变量时,所有内容都是笨拙的,并且得到了整齐的打印输出,如YYYY-MM-DD,而不是datetime.date(2010,1,4)的日期形式。 Now what I need to do is get this nice, post-sorted, list to be able to be used for keys in a dictionary. 现在,我需要做的是得到这个不错的,后排序的列表,以便能够将其用作字典中的键。 I have keys that are also in the form YYYY-MM-DD. 我也有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? 为什么当我尝试使用日期对象列表上带有点的变量作为字典history的键值时,它不起作用?

A date object is hashable . date对象是可哈希的 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. 但这并不意味着将date对象散列到您使用的人类可读的字符串表示形式(或查看何时打印日期对象),因为进行散列并转换为字符串的__hash____str__ date方法不一定相同。

You could try histodict[str(start)]['Open'] (ie, convert the date variable to a string by using the __str__ method of date objects before using it as a key). 您可以尝试histodict[str(start)]['Open'] (即,在将日期变量用作键之前,使用日期对象的__str__方法将日期变量转换为字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM