how to find position of dictionary values

Terry Reedy tjreedy at udel.edu
Mon Sep 1 15:08:30 EDT 2008



Alexandru Palade wrote:
 > lookfor = 'dfsdf'
 > for item, value in kev.items():
 >        if lookfor in value:
 >                print item
 >                print value.index(lookfor)
 >                break   # assuming you only want one result

slight variation:

lookfor = 'dfsdf'
for item, value in kev.items():
     for i, val in enumerate(value):
         if val == lookfor:
             print item, i
             break   # assuming you only want one result
else:
     print lookfor, 'not found'

This is what for-else is meant for.

If you want 0 to many lookfor occurences,

lookfor = 'dfsdf'
hits = []
for item, value in kev.items():
     for i, val in enumerate(value):
         if val == lookfor:
             hits.append((item, i))

print hits

One-liner fanatics would, of course, rewrite this as

hits = [(item, i) for item, value in kev.items() for i, val in 
enumerate(value) if val == lookfor]

Terry Jan Reedy



tjr




More information about the Python-list mailing list