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

Python 如何从字典中检索多个项目对,python,for-loop,dictionary,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-项目1,2-项目2 3-项目3,4-项目4 编辑-使其看起来像上面所示这是您想要的吗: a = {1:'item 1', 2:'item 2', 3:'item 3', 4:'item 4' } f

有人知道我如何从字典中检索两对吗 我试图以更紧凑的格式呈现数据

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-项目1,2-项目2

3-项目3,4-项目4

编辑-使其看起来像上面所示

这是您想要的吗:

a = {1:'item 1', 2:'item 2', 3:'item 3', 4:'item 4' }

for i,j in a.items():
    print i, ' - ' ,j, ',',

[OUTPUT]
1 - item 1 , 2 - item 2 , 3 - item 3 , 4 - item 4 ,
或者更简单地说

l = [' - '.join(map(str, i)) for i in a.items()]

>>> print 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
另一种获得配对的方法是使用以下技巧:


@A的可能副本श威尼च豪德利,能解释一下我的错误吗?感谢您将此
1-项目1、2-项目2、3-项目3、4-项目4
与您的输出进行比较。@Aश威尼च豪德利,你是说我额外的
在2到3之间吗?对不起,我错了!它满足了我的要求,但我的要求是错误的:(-我按照我的要求编辑了输出。你的示例完全取决于打印语句末尾的逗号。-cheersAgain,我很抱歉!-我没有按照我真正想要的方式表示输出。你的方法完美地实现了我最初的要求。Cheers@FloggedHorse这应该可以做到:
对于分组:打印中的x“{}-{},{}-{}”。格式(*chain(*x))
>>> 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