0

(Python 2.7) In my previous question, I was trying to iterate through the keys of the dictionary "rooms" and show only two keys per line, how can I go about showing an odd number of rooms at a time? More specifically, two per line until only one is left and only that one will go on a line on its own.

Previous Question

Current Code:

rooms = {
"101": "Classroom",
"102": "Bathroom",
"103": "Room",
"104": "Room",
"105": "Room",
"106": "Room"}


keys = iter(sorted(rooms.keys()))
for key in keys:
    print key + "    " + next(keys)

Current Output:

101    102
103    104
105    106

Goal Output:

101    102
103    104
105    106
107
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • How's that possible if you have an even number of keys (like you do in your example dictionary)? – slider Oct 31 '18 at 15:20

3 Answers3

1

next() takes an optional second argument for a default value to return when the iterator is exhausted.

keys = iter(sorted(rooms.keys()))
for key in keys:
    print key + "    " + next(keys, "")
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
0
rooms = {
"101": "Classroom",
"102": "Bathroom",
"103": "Room",
"104": "Room",
"105": "Room",
"106": "Room",
"107": "Room"}


keys = iter(sorted(rooms.keys()))
for key in keys:
    try:
        print(key + "    " + next(keys))
    except StopIteration:
        print(key)

Though it might be a lot simpler to make keys a list and just check if you've reached the end.

DonQuiKong
  • 413
  • 4
  • 15
0

Alternatively use enumerate.

from __future__ import print_function

per_line = 2
keys = iter(sorted(rooms.keys()))
for i, key in enumerate(keys):
    if (i + 1) % per_line == 0 or (i + 1) == len(rooms.keys()):
        print(key)
    else:
        print(key, end="\t")
CJR
  • 3,916
  • 2
  • 10
  • 23