迭代嵌套字典

时间:2014-07-23 14:50:17

标签: python dictionary

下面是我为项目创建的字典。我试图迭代列表值但不断收到错误

moo = {'dell': {'strengths': {'dell strengths': ['http://www.strategicmanagementinsight.com/swot-analyses/dell-swot-analysis.html',
    'http://www.academia.edu/3687086/Strategic_Management_case_analysis_DELL']},
  'weekness': {'dell weekness': ['http://www.strategicmanagementinsight.com/swot-analyses/dell-swot-analysis.html',
    'http://www.123helpme.com/dell-strength-and-weakness-view.asp%3Fid%3D164569']}},
 'ibm': {'strengths': {'ibm strengths': ['http://www.forbes.com/sites/stevedenning/2011/07/10/why-did-ibm-survive/',
    'http://www.strategicmanagementinsight.com/swot-analyses/ibm-swot-analysis.html']},
  'weekness': {'ibm weekness': ['http://www.quora.com/IBM/What-are-the-weaknesses-of-IBM',
    'http://www.marketingteacher.com/ibm-swot/']}}}

for k in moo.keys():
#base.add_sheet(k)
    for sk in moo[k].keys():
    #print sk
        for mk in moo[k][sk].keys():
            moo[k][sk][mk] = googlelinks(mk,2)
            for v in moo[k][sk][mk].items():
                print v

错误:

AttributeError: 'list' object has no attribute 'items'

我在做一些非常错误的事情。请帮忙

1 个答案:

答案 0 :(得分:1)

听起来googlelinks()正在返回一个列表,而不是字典。您只需使用for v in moo[k][sk][mk]:进行迭代即可。除非你特别使用字典,否则不需要items()

编辑:目前还不清楚为什么你在大多数代码中使用keys()而后来items()使用items()moo[k][sk][mk]函数将返回给定字典项的键和值,这样可以大大简化代码。您可以通过执行类似的操作来消除for k, v in moo.items(): # v = moo[k] #base.add_sheet(k) for sk, sv in v.items(): # sv = v[sk] = moo[k][sk] #print sk for mk, mv in sv.items(): # mv = sv[mk] = v[sk][mk] = moo[k][sk][mk] sv[mk] = googlelinks(mk,2) for gv in sv[mk]: print gv 之类的嵌套调用(感谢Martijn):

{{1}}

另一方面,您可能希望为变量提供较少的神秘名称,因此您的代码更容易理解。理想情况下,我们应该通过阅读变量名来了解每个字典中存储的内容。