Rorschach - 1 year ago 71
Python Question

# Move through keys in a dictionary in an order python3

I have a dictionary like this:

``````{(4, 4, 'TO'): '1.0', (5, 3, 'NNP'): '0.061274509803921566', (3, 3, 'VBP'): '0.07894736842105263', (3, 3, 'VB'): '0.012048192771084338', (2, 2, 'X_TO'): '1.0', (0, 0, 'NP_PRP'): '0.3235294117647059', (6, 6, 'NNP'): '0.051470588235294115', (1, 2, 'VBP'): '0.02631578947368421', (2, 3, 'TO'): '1.0', (4, 4, 'X_TO'): '1.0'}
``````

Where keys are tuples of (int, int str).

I want to loop over it (in a for loop) in the order of the leftmost tuple integer least to greatest. So, it would first loop:
`(0, 0, 'NP_PRP')`
then
`(1, 2, 'VBP')`
. Order after the first integer doesnt matter.

Then do that. Tuples automatically sort by first element order. (then second element order, etc).

``````d = {(4, 4, 'TO'): '1.0', (5, 3, 'NNP'): '0.061274509803921566', (3, 3, 'VBP'): '0.07894736842105263', (3, 3, 'VB'): '0.012048192771084338', (2, 2, 'X_TO'): '1.0', (0, 0, 'NP_PRP'): '0.3235294117647059', (6, 6, 'NNP'): '0.051470588235294115', (1, 2, 'VBP'): '0.02631578947368421', (2, 3, 'TO'): '1.0', (4, 4, 'X_TO'): '1.0'}

for T in sorted(d):
print(T)

#(0, 0, 'NP_PRP')
#(1, 2, 'VBP')
#(2, 2, 'X_TO')
#(2, 3, 'TO')
#..
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download