迭代字典并从内部字典中获取值

时间:2011-07-29 08:26:55

标签: 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')}

我想遍历字典,找出日期是否等于今天的日期,然后使用内部字典构建一个url,使用第一个值作为slug。能够迭代,但我不知道如何获取内部值

# will only print dates
for i in dic:
 print i

2 个答案:

答案 0 :(得分:6)

在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]

详细了解dictionaries and supported methods

答案 1 :(得分:0)

如果你想访问该值,那么你下标字典,除非你真的想要元组,这通常比使用.items().iteritems()方法更麻烦:

for i in dic:
 print i, dic[i]
顺便说一下,你说'内部字典',但你只有一个字典,值是元组。