Skip to content Skip to sidebar Skip to footer

Python - Looping Through A Multidimensional Dictionary

If I explain what I think I am doing, I hope someone can explain where I am going wrong. I have the following dictionary: ls = [{ 'The Wolf Gift (13)': { 'cover': 'V:\\

Solution 1:

Her is an example that could be used if ls contained more than one dictionary.

for dic inls:
    for key in dic:
        print'Book Name: %s' % (key)
        for value in dic[key]:
            print'\t%s: %s' % (value, dic[key][value])

This will produce the following output:

Book Name:Mummy(14)year:1989cover:V:\Books\AnneRice\Mummy(14)\cover.jpgauthor:AnneRiceBook Name:TheWolfGift(13)year:1988cover:V:\Books\AnneRice\TheWolfGift(13)\cover.jpgauthor:AnneRice

Or you could remove the final for loop and access the keys directly like so:

for dic inls:
    for key in dic:
        print'Book Name: %s' % (key)
        print'Publish Year: %s' % dic[key]['year']

which will give the following output:

Book Name:Mummy(14)Publish Year:1989Book Name:TheWolfGift(13)Publish Year:1988

Solution 2:

It's a list containing a single dictionary. You can do something like:

>>>books = ls[0]>>>for book, details in books.iteritems():
        print book,'-->', details['cover']
...
Mummy (14) --> V:\Books\Anne Rice\Mummy (14)\cover.jpg
The Wolf Gift (13) --> V:\Books\Anne Rice\The Wolf Gift (13)\cover.jpg

Solution 3:

ls is a list that contains a dictionary. This dictionary contains keys which are the books, and the values are dictionaries. So you can access them like this:

for book inls[0]:
    covername = ls[0][book]['cover']
    print(covername) 

which prints:

V:\Books\Anne Rice\The Wolf Gift (13)\cover.jpgV:\Books\Anne Rice\Mummy (14)\cover.jpg

ls[0] refers to the first element in the list

[book] is because the keys of the dict are being iterated

['cover'] is the element being read from the dict refered to by [book]

Solution 4:

OK, so first of all your dictionary is actually a list containing a dictionary (you've got [] around its declaration). This might be a problem. Once you know this it's pretty easy to get all you want. For example:

for key inls[0].keys():
     printls[0][key]

Or, if you want to access particular detail about each book (contained in yet another dictionary within the outermost one holding each book):

forbookKeyinls[0].keys():
     printls[0][bookKey]['cover']printls[0][bookKey]['author']printls[0][bookKey]['year']

Hope this helps. Maybe consider getting rid of this list around all this, will make your life a bit easier (one less index to use).

Post a Comment for "Python - Looping Through A Multidimensional Dictionary"