过滤特定字典

时间:2010-11-10 10:56:00

标签: python dictionary filter

d = {'id': 'ccccc',
     'school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11', 'city':'yy'}]}

我想使用s_id过滤它。假设某人想要过滤s_id = 11它应该返回{'s_id': '11', 'city':'yy'}.请使用过滤器关键字回答。

3 个答案:

答案 0 :(得分:2)

只需使用python内置过滤功能:

>>> filter(lambda d:d['s_id']=='11',d['school'])
[{'s_id': '11', 'city': 'yy'}]

作为奖励,如果你想按's_id'排序 你可以这样做:

>>> for school in sorted(d['school'],key=lambda d:d['s_id']):
...     print school
... 
{'s_id': '11', 'city': 'yy'}
{'s_id': '12', 'city': 'xxx'}

答案 1 :(得分:0)

>>> s_id=11
>>> [i for i in d['school'] if i['s_id'] == str(s_id)]
[{'s_id': '11', 'city': 'yy'}]

答案 2 :(得分:0)

这是使用filter和部分功能。

#!/usr/bin/env python

from functools import partial

d = {'id': 'ccccc','school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11',
'city':'yy'}]}

def myfilter(school, s_id):
    return school['s_id'] == str(s_id)

f = partial(myfilter, s_id = 11)
print filter(f, d['school'])