Python - 循环遍历多维字典 [英] Python - Looping through a multidimensional dictionary

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

问题描述

如果我解释我认为我在做什么,我希望有人能解释我哪里出错了.

我有以下字典:

ls = [{'狼的礼物(13)':{'cover': 'V:\\Books\\Anne Rice\\The Wolf Gift (13)\\cover.jpg','作者':'安妮赖斯','年':'1988'},'木乃伊(14)':{'cover': 'V:\\Books\\Anne Rice\\Mummy (14)\\cover.jpg','作者':'安妮赖斯','年':'1989'},}]

首先上面是多维字典吗?我想确保我在谈论正确的事情.其次,我如何遍历它以检索各个级别的信息.字典是动态填充的,所以我事先不知道键.

我尝试过 for book in lsbook['cover'] 等等,但它似乎不起作用.我需要书名,然后是每本书的附加信息(封面等).我对python很陌生.我来自 PHP,使用数组是我的生计,但是 python 正在杀死我....

谢谢

解决方案

这是一个包含单个字典的列表.您可以执行以下操作:

<预><代码>>>>书籍 = ls[0]>>>对于书籍,books.iteritems() 中的详细信息:打印书,'-->',详细信息['封面']...木乃伊 (14) -->V:\Books\Anne Rice\Mummy (14)\cover.jpg狼的礼物 (13) -->V:\书籍\安妮·赖斯\狼的礼物(13)\cover.jpg

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

解决方案

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

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

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