Python for key, value in dictionary

21,835

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
Share:
21,835
willstaff
Author by

willstaff

Updated on August 08, 2021

Comments

  • willstaff
    willstaff over 2 years

    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.

  • willstaff
    willstaff about 9 years
    Is there a way to select two at a time?
  • Filadelfo
    Filadelfo about 9 years
    items() returns a list, You can use an index to get the i-th element and then i-th + 1 element, but You must pay attention to the length of the list.
  • acidjunk
    acidjunk over 4 years
    perv should be prev(ious)_key ?