9

So as of now this is my code:

for keys, values in CountWords.items():
    val = values
    print("%s: %s \t %s: %s" % (keys, val, keys, val))

When this is printed it will output this the key and its value and then after a space the same thing. What I want to know is if I can get the second %s: %s to select the next key and value from the dictionary.

Joshua
  • 40,822
  • 8
  • 72
  • 132
willstaff
  • 101
  • 1
  • 1
  • 5
  • Be aware that results can differ per python implementation. Dictionary's are not explicitly ordered until python3.7, so referring to the next item could be unambiguous: https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744 – acidjunk Aug 22 '19 at 07:19
  • It's not clear how you wanted this to work: the second time through the list, should it use the second and third key-value pairs (overlapping adjacent pairs)? Or the third and fourth (iterating in chunks of size 2)? Either way, this is a common problem with a better canonical duplicate. Keep in mind that any "lazy" technique for iterating over a list will generally apply to any iterable, such as a dict's `.items` in 3.x (or `.iteritems` in 2.x). – Karl Knechtel May 05 '23 at 02:47

2 Answers2

14

Instead of trying to get next k-v pair, you can keep current k-v pair and use them on the next iteration

d = {'foo': 'bar', 'fiz': 'baz', 'ham': 'spam'}

prev_key, prev_value = None, None

for key, value in d.items():
    if prev_key and prev_value:
        print("%s: %s \t %s: %s" % (prev_key, prev_value, key, value))
    prev_key, prev_value = key, value

fiz: baz     foo: bar
foo: bar     ham: spam
Timothy Alexis Vass
  • 2,526
  • 2
  • 11
  • 30
0

the items() method returns a list of tuple. Inside a for loop, You'are choosing an element one at time, You can't point within the loop the next element.

Filadelfo
  • 86
  • 4