8

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

我有以下字典:

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'
    },
}]

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

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

谢谢

4

4 回答 4

6

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
于 2013-08-10T21:56:57.673 回答
5

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

>>> 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
于 2013-08-10T21:41:29.137 回答
4

ls 是一个包含字典的列表。这个字典包含的键是书,值是字典。所以你可以像这样访问它们:

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

打印:

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

ls[0] 引用列表中的第一个元素

[book] 是因为 dict 的键正在被迭代

['cover'] 是从 [book] 引用的字典中读取的元素

于 2013-08-10T21:52:14.233 回答
2

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 in ls[0].keys():
     print ls[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):

for bookKey in ls[0].keys():
     print ls[0][bookKey]['cover']
     print ls[0][bookKey]['author']
     print ls[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).

于 2013-08-10T21:54:53.877 回答