Skip to main content
 首页 » 编程设计

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

2025年05月04日19lovecherry

我正在尝试构建一个不确定如何使用 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 

请您参考如下方法:

在 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 的信息