tags:

views:

112

answers:

4

I can filter the following dictionary like:

data = {
    1: {'name': 'stackoverflow', 'traffic': 'high'},
    2: {'name': 'serverfault', 'traffic': 'low'},
    3: {'name': 'superuser', 'traffic': 'low'},
    4: {'name': 'mathoverflow', 'traffic': 'low'},
}

traffic = 'low'

for k, v in data.items():
    if v['traffic'] == traffic:
        print k, v

Is there an alternate way to do the above filtering?

+1  A: 

In principle — no. You could rewrite the code slightly, but it would still do the same — iterating through all the values.

doublep
+2  A: 

Sure, but they're all brute-force.

dict((k, v) for (k, v) in data.iteritems() if v['traffic'] == traffic)
Ignacio Vazquez-Abrams
+2  A: 

At some level the filter will have to do exactly what you describe. If you're going to filter on the values, you'll have to process each one, one-by-one.

John Weldon
+2  A: 

If you're doing this a lot, you could have two dictionaries, one for each direction. The new dictionary will map values to lists of values. This is a good idea if you will be doing this reverse lookup more than once.

Brian