am trying to build a logic which am not quit sure how to do with python. I have the following dictionary
{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')}
I want to iterate through the dictionary, find out if the date is equal today's开发者_如何学Python date and then use the inner dictionary to build a url using the first value as a slug. Am able to iterate but I don't know how to fetch the inner value
# will only print dates
for i in dic:
print i
In python when you use 'for x in dic' it is the same as to use 'for x in dic.keys()' - you are iterating trough only keys not (key,value) pairs. To do what you want you can take a look at the items() and iteritems() dictionary methods, they allows you to get access to (key,value) pairs:
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]
Read more about dictionaries and supported methods
If you want to access the value then you subscript the dictionary, unless you actually want tuples this is usually less hassle than using either .items()
or .iteritems()
methods:
for i in dic:
print i, dic[i]
BTW, you say 'inner dictionary' but you only have one dictionary, the values are tuples.
精彩评论