遍历嵌套字典 [英] iterate over nested dictionaries

查看:63
本文介绍了遍历嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是我为项目创建的字典.我正在尝试遍历列表值,但不断出现错误

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

错误:

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

我在这里做错了什么.请帮助

I am doing something terribly wrong here. Please help

推荐答案

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

It sounds like googlelinks() is returning a list, not a dictionary. You just iterate over that using for v in moo[k][sk][mk]:. No need for items() unless you're using a dictionary in particular.

目前尚不清楚为什么对大多数代码使用 keys(),而稍后对 items()使用它们. items()函数将返回给定字典项的键和值,这使您可以大大简化代码.您可以通过执行以下操作来消除 moo [k] [sk] [mk] 之类的嵌套调用(感谢Martijn):

it's unclear why you're using keys() for most of the code and them items() later. The items() function will return both the key and the value for a given dictionary item, which lets you simplify your code greatly. You can eliminate nested calls like moo[k][sk][mk] by doing something like this instead (thanks 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.

这篇关于遍历嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆