1

Does anyone know how I retrieve two pairs from a dictionary I'm trying to present data in a more compact format

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

edit - sorry ment it to look like above

Floggedhorse
  • 694
  • 8
  • 15
  • 1
    possible duplicate of [Having list of keys, get list/tuple of values from dict](http://stackoverflow.com/questions/23156853/having-list-of-keys-get-list-tuple-of-values-from-dict) – jonrsharpe Apr 23 '14 at 07:43

2 Answers2

3

You can use iter() to convert the sorted items to an iterator, and then loop over that iterator to get the pairs.

>>> 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

Another way to get the pairs is to use the zip(*[iter(seq)]*n) trick:

>>> 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
Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Again, my apologies! - I had not represented the output how I truly wanted it. Your method worked perfectly to produce what I originally asked for. Cheers – Floggedhorse Apr 23 '14 at 09:41
  • @FloggedHorse This should do it: `for x in grouped: print '{} - {} , {} - {}'.format(*chain(*x))` – Ashwini Chaudhary Apr 23 '14 at 09:43
0

Is this what you want:

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 ,

Or even more simply

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

>>> print l
1 - item 1, 2 - item 2, 3 - item 3, 4 - item 4
sshashank124
  • 31,495
  • 9
  • 67
  • 76