I'm working on a program that requires me to loop a dictionary two keys at a time. Here's a simple representation of my dictionary.
my_dict = {
'LAP0-1': 146.48,
'LAP1-1':44.11,
'LAP2-1':25.54,
'LAP3-1':75.29,
'LAP5-2':85.76,
'LAP6-2':46.87
}
# loop dictionary 1 key at a time
for k,v in my_dict:
print k + " | " + v;
I know if I had a list, I could loop the items 2 at a time like so:
for i in range(0, len(my_list), 2):
print my_list[i] + " | " + my_list[i+1];
But is it possible to loop the dictionary two keys at a time?
I want to print out the following in a loop:
LAP0-1 | 146.48 ; LAP1-1 | 44.11
LAP1-1 | 44.11 ; LAP2-1 | 25.54
LAP2-1 | 75.29 ; LAP3-1 | 85.76
LAP5-2 | 85.76 ; LAP6-2 | 46.87
Another solution I thought of but won't for my case is this:
for i in range(0, len(my_list), 2):
print my_dict[my_list[i]] + " | " my_dict[my_list[i+1]];
where my_list[i]
is'LAP0-1'
and my_list[i+1]
is 'LAP1-1'
. It just seems inefficient having to store keep 2 data structures like that. How do I loop a dictionary two keys at a time?
from collections import OrderedDict
from itertools import tee
my_dict = OrderedDict([
('LAP0-1', 146.48),
('LAP1-1', 44.11),
('LAP2-1', 25.54),
('LAP3-1', 75.29),
('LAP5-2', 85.76),
('LAP6-2', 46.87)
])
# pairwise() from Itertools Recipes
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for (key1, value1), (key2, value2) in pairwise(my_dict.items()):
print("{} | {} ; {} | {}".format(key1, value1, key2, value2))
OUTPUT
LAP0-1 | 146.48 ; LAP1-1 | 44.11
LAP1-1 | 44.11 ; LAP2-1 | 25.54
LAP2-1 | 25.54 ; LAP3-1 | 75.29
LAP3-1 | 75.29 ; LAP5-2 | 85.76
LAP5-2 | 85.76 ; LAP6-2 | 46.87
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With