遍历字典并获取内部字典的值

1 投票
2 回答
1632 浏览
提问于 2025-04-16 22:29

我正在尝试用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')}

我想遍历这个字典,检查日期是否等于今天的日期,然后使用里面的字典来构建一个网址,使用第一个值作为网址的一部分。我可以遍历字典,但不知道怎么获取里面的值。

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

2 个回答

0

如果你想获取字典里的值,可以直接用下标来访问,除非你真的想要元组(tuple),这样做通常比使用 .items().iteritems() 方法要简单得多。

for i in dic:
 print i, dic[i]

顺便说一下,你提到的“内部字典”,其实你只有一个字典,里面的值是元组。

6

在Python中,当你使用'for x in dic'时,这和使用'for x in dic.keys()'是一样的——你只是在遍历字典的键,而不是键值对(key,value)。

如果你想要获取键值对,可以看看字典的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]

想了解更多关于字典和支持的方法的信息,可以去看看。

撰写回答