python - 如何从字典中检索多个项目对

标签 python for-loop dictionary

有谁知道我如何从字典中检索两对 我正在尝试以更紧凑的格式呈现数据

a = {1:'item 1', 2:'item 2', 3:'item 3', 4:'item 4' }
for i,j,k,l in a:
    print i, ' - ' ,j , ' , ' ,k, ' - ' ,l

1 - item 1 , 2 - item 2

3 - item 3 , 4 - item 4

编辑 - 抱歉将其修改为上面的样子

最佳答案

您可以使用 iter() 将排序后的项转换为迭代器,然后循环该迭代器以获取对。

>>> from itertools import chain
>>> items =  iter(sorted(a.items())) #As dicts are unordered
>>> print ' '.join('{} - {} , {} - {}'.format(*chain(x, next(items))) for x in items)
1 - item 1 , 2 - item 2 3 - item 3 , 4 - item 4

获取配对的另一种方法是使用 zip(*[iter(seq)]*n)技巧:

>>> items = sorted(a.items())
>>> grouped = zip(*[iter(items)]*2)
>>> print ' '.join('{} - {} , {} - {}'.format(*chain(*x)) for x in grouped)
1 - item 1 , 2 - item 2 3 - item 3 , 4 - item 4

关于python - 如何从字典中检索多个项目对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23237925/

相关文章:

python - 匿名列表如何在 python 列表理解中工作?

c - 当未声明的变量传递到 for 循环并更改 for 循环语法时会发生什么

java - 为什么它会跳过数组索引 0?

python - Python 中的交叉引用列表

python - 根据其他列表对字典中的列表进行排序,而无需再次分配它们

python - 找到页面上第二个特定的链接文本元素并通过python点击它

python - 在python中使用re查找关键字旁边的两个字符串

python - OpenCV2 - 在实例化 VideoWriter 对象时抑制压缩对话框

python - 从 Ruby 到 Python - 是否有 "try"的等价物?

c# - C# 中的泼溅