开发者

What's the non brute force way to filter a Python dictionary?

开发者 https://www.devze.com 2022-12-28 15:11 出处:网络
I can filter the following dictionary like: data = { 1: {\'name\': \'stackoverflow\', \'traffic\': \'high\'},

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 a开发者_运维技巧bove filtering?


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.


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.


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


Sure, but they're all brute-force.

dict((k, v) for (k, v) in data.iteritems() if v['traffic'] == traffic)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号