Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Looping through a multidimensional dictionary [duplicate]

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:\\Books\\Anne Rice\\The Wolf Gift (13)\\cover.jpg',
        'author': 'Anne Rice',
        'year': '1988'
    },
    'Mummy (14)': {
        'cover': 'V:\\Books\\Anne Rice\\Mummy (14)\\cover.jpg',
        'author': 'Anne Rice',
        'year': '1989'
    },
}]

First of all is the above a multidimensional dictionary? I want to make sure I am talking about the right thing. Secondly, how do I loop through it to retrieve the information at the various levels. The dictionary is dynamically populated so I do not know the keys before hand.

I have tried for book in ls and then book['cover'] etc.. but it doesn't seem to work. I need the book name, and then the additional info for each book (cover etc...). I am pretty new to python. I come from PHP and using arrays are my bread and butter, but python is killing me....

Thanks

like image 640
superphonic Avatar asked Aug 10 '13 21:08

superphonic


1 Answers

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

for dic in ls:
    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: 1989
    cover: V:\Books\Anne Rice\Mummy (14)\cover.jpg
    author: Anne Rice
Book Name: The Wolf Gift (13)
    year: 1988
    cover: V:\Books\Anne Rice\The Wolf Gift (13)\cover.jpg
    author: Anne Rice

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

for dic in ls:
    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: 1989
Book Name: The Wolf Gift (13)
Publish Year: 1988
like image 147
Bryan Avatar answered Sep 19 '22 21:09

Bryan