简体   繁体   English

遍历嵌套字典

[英]iterate over nested dictionaries

below is a dictionary that i have create for a project. 下面是我为项目创建的字典。 I am trying to iterate over the list values but keep getting errors 我正在尝试遍历列表值,但不断收到错误

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

Error: 错误:

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

I am doing something terribly wrong here. 我在这里做错了什么。 Please help 请帮忙

It sounds like googlelinks() is returning a list, not a dictionary. 听起来googlelinks()正在返回列表,而不是字典。 You just iterate over that using for v in moo[k][sk][mk]: . 您只需遍历for v in moo[k][sk][mk]: No need for items() unless you're using a dictionary in particular. 除非您特别使用字典,否则不需要items()

EDIT: it's unclear why you're using keys() for most of the code and them items() later. 编辑:目前尚不清楚为什么要对大多数代码使用keys() ,以后再对它们使用items() The items() function will return both the key and the value for a given dictionary item, which lets you simplify your code greatly. items()函数将返回给定字典项的键和值,这使您可以大大简化代码。 You can eliminate nested calls like moo[k][sk][mk] by doing something like this instead (thanks Martijn): 您可以改为执行以下操作来消除类似moo[k][sk][mk]类的嵌套调用(感谢Martijn):

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

On another note, you may want to give your variables less cryptic names, so your code is easier to follow. 另一个需要注意的是,您可能希望给变量赋予较少的隐名,以便代码易于理解。 Ideally, we should know from reading your variable names what's stored in each dictionary. 理想情况下,我们应该通过读取变量名知道每个字典中存储了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM