d = {'id': 'ccccc',
'school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11', 'city':'yy'}]}
我想使用s_id对其进行过滤。假设如果某人想过滤s_id = 11
它应该返回{'s_id': '11', 'city':'yy'}.
请使用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'}.
请使用filter关键字回答。过滤特定字典
>>> s_id=11
>>> [i for i in d['school'] if i['s_id'] == str(s_id)]
[{'s_id': '11', 'city': 'yy'}]
这是使用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'])
只需使用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'}
*请回答它使用过滤器关键字。*这是一个家庭作业吗?你有什么尝试? – SilentGhost 2010-11-10 11:02:40
请阅读5.1.3 http://docs.python.org/tutorial/datastructures.html – soulseekah 2010-11-10 11:09:33
请遵循[general](http://tinyurl.com/so-hints)问题[准则](http:// meta .stackexchange.com/q/10812):陈述任何特殊的限制,展示你到目前为止所尝试的内容,并询问具体是什么让你感到困惑。 – 2010-11-10 17:14:15