简体   繁体   English

以值作为列表遍历字典

[英]Iterating over a dictionary with value as a list

I've a dictionary 'mydict'. 我有一本字典“ mydict”。

{   'a': ['xyz1', 'xyz2'],
    'b': ['xyz3', 'xyz4'],
    'c': ['xyz5'],
    'd': ['xyz6']}

I'm trying to print out all the keys and values of this dictionary using the following code: 我正在尝试使用以下代码打印出该词典的所有键和值:

for username, details in mydict.iteritems():
    pprint.pprint(username + " " + details)

But, I'm getting the following error: 但是,出现以下错误:

AttributeError: 'list' object has no attribute 'iteritems'

Any help would be appreciated. 任何帮助,将不胜感激。

This code works on your example 此代码适用于您的示例

>>> import pprint
>>> mydict = {   'a': ['xyz1', 'xyz2'],
    'b': ['xyz3', 'xyz4'],
    'c': ['xyz5'],
    'd': ['xyz6']}

>>> for username, details in mydict.iteritems():
        pprint.pprint((username, details))


('a', ['xyz1', 'xyz2'])
('c', ['xyz5'])
('b', ['xyz3', 'xyz4'])
('d', ['xyz6'])

I get the same AttributeError when I attempt the original, this arrises becuase the VALUE in each KEY, VALUE pair is a list. 当我尝试原始时,会得到相同的AttributeError,这是由于每个KEY中的VALUE引起的,VALUE对是一个列表。

Using mydict.items() you can create a copy of each (KEY, VALUE) pair, which you can then print: 使用mydict.items()可以创建每个(键,值)对的副本,然后可以打印:

for key, value in mydict.items():
    print((key, value))

Though of course, creating a copy using items() is memory expensive if your dictionary is large. 当然,如果字典很大,则使用items()创建副本会占用大量内存。 Which, is the big advantage (lower memory cost, more efficient AND * optimised for python *) of being able to use iteritems() to iterate through your dictionary. 这是能够使用iteritems()遍历字典的最大优势(更低的内存成本,更高效的AND * 针对 python * 优化 )。

Equally well, you could do the following: 同样,您可以执行以下操作:

for key in d:
    print((k, mydic[key]))

BUT (in python), this is slower again! 但是(在python中),这又变慢了! Because you have to re-hash the dictionary each time as you look up mydict[key] . 因为每次查找mydict[key]时都必须重新哈希字典。 So, it seems that mydict.items() is the best option here, as it gives you access to the values directly through tuple unpacking. 因此,似乎mydict.items()是此处的最佳选择,因为它使您可以直接通过元组拆包访问值。

Raymond Hettinger (the iteritems and generator guru from Python) gave a great talk at US PyCon, which you can watch here: http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho Raymond Hettinger(Python的迭代器和生成大师)在美国PyCon上发表了精彩演讲,您可以在此处观看: http : //pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM