0

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Raghav Shaligram
  • 309
  • 4
  • 11

1 Answers1

1

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.

EDIT: 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.

TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42