# Python 匿名表达式 Python 高阶函数编程,使用 lambda 表达式获取key,将list转成dict ```python def list_to_dict(list, key_func): d = {} for item in list: k = key_func(item) v = item list = d.get(k) if list is None: d[k] = [v] else: d[k].append(v) return d if __name__ == '__main__': list = [ {"name": "alice", "age": 100}, {"name": "middle", "age": 100}, {"name": "bob", "age": 200} ] # TODO(You): 请在此调用 list_to_dict 方法,将 list 转成dict print(ret) ``` 请选出下列**实现错误**的选项。 ## template ```python def list_to_dict(list, key_func): d = {} for item in list: k = key_func(item) v = item list = d.get(k) if list is None: d[k] = [v] else: d[k].append(v) return d if __name__ == '__main__': list = [ {"name": "alice", "age": 100}, {"name": "middle", "age": 100}, {"name": "bob", "age": 200} ] ret = list_to_dict(list, lambda item: item['age']) print(ret) ``` ## 答案 ```python ret = list_to_dict(list, lambda item: item['age'] ) ``` ## 选项 ### A ```python ret = list_to_dict(list, lambda item: item['age']) ``` ### B ```python def get_key(item): return item['age'] ret = list_to_dict(list, get_key) ``` ### C ```python get_key = lambda item: item['age'] ret = list_to_dict(list, get_key) ```