2

I am trying to iterate through the keys of the dictionary "rooms" and show only two keys per line.

Current code: (Python 2.7)

rooms = {
"105": "Room",
"128": "Room",
"101": "Room",
"102": "Room",
"103": "Room",
"104": "Room"}

for room, nextroom in zip(rooms.keys(), rooms.keys()[1:]):
    print room, nextroom

Current output:

102 128
128 103
103 101
101 104
104 105

Goal output:

102 128
103 101
104 105
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • Hi JonMichael Book, welcome to Stackoverflow. 1) Is this in Python? The code looks like it is Python but I wanted to double check. 2) It is not very clear from the post above how to get the goal output. Can you elaborate more on that? – Francis Oct 29 '18 at 02:14
  • Sorry! Yes, this is Python. I am using Python 2.7. – JonMichael Book Oct 29 '18 at 02:22
  • @Francis I am trying to iterate through the keys of the dictionary "rooms" and show only two values per line. – JonMichael Book Oct 29 '18 at 02:30
  • Try `for room, nextroom in zip(rooms.keys()[::2], rooms.keys()[1::2])` and check out [Understanding python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) – pault Oct 29 '18 at 02:49

2 Answers2

4

You can use iter:

keys = iter(rooms.keys())
for key in keys:
    print key, next(keys)
1

Once you cast the keys to a list, it's just a matter of walking through that list and grabbing them in batches of two. In Python 2 you can use xrange along with the following arguments to get the intended effect:

room_keys = rooms.keys()

for i in xrange(0, len(rooms), 2): 
  print room_keys[i], room_keys[i + 1]
brianz
  • 7,268
  • 4
  • 37
  • 44