Mo *_*abi 1 python dictionary iterator
我正在尝试构建一个逻辑,它不会放弃如何处理python.我有以下字典
{datetime.datetime(2011, 7, 18, 13, 59, 25): (u'hello-world', u'hello world'), datetime.datetime(2011, 7, 17, 15, 45, 54): (u'mazban-archeticture', u'mazban arch'), datetime.datetime(2011, 7, 7, 15, 51, 49): (u'blog-post-1', u'blog post 1'), datetime.datetime(2011, 7, 8, 15, 54, 5): (u'blog-post-2', u'blog post 2'), datetime.datetime(2011, 7, 18, 15, 55, 32): (u'blog-post-3', u'blog post 3')}
Run Code Online (Sandbox Code Playgroud)
我想遍历字典,找出日期是否等于今天的日期,然后使用内部字典构建一个url,使用第一个值作为slug.能够迭代,但我不知道如何获取内部值
# will only print dates
for i in dic:
print i
Run Code Online (Sandbox Code Playgroud)
在python中,当你使用'for x in dic'时,它与使用'for x in dic.keys()'相同 - 你只通过键而不是(键,值)对迭代.要做你想做的事,你可以看看items()和iteritems()字典方法,它们允许你访问(键,值)对:
for key,value in dic.iteritems():
if key == datetime.today(): # or (datetime.today() - key).seconds == <any value you expect>
# since value is a tuple(not a dict) and you want to get the first item you can use index 0
slug = value[0]
Run Code Online (Sandbox Code Playgroud)
阅读有关字典和支持方法的更多信息
归档时间: |
|
查看次数: |
1614 次 |
最近记录: |