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?