如何从字典列表提取值到字符串数组?解决items()报错问题
问题解决方案
错误原因很直接:你把列表对象当成单个字典来操作了。你的States_dict实际是包含多个字典的列表,而.items()是字典的专属方法,列表没有这个属性,所以会触发AttributeError。
下面是几种可行的解决方法:
1. 基础循环遍历
逐个取出列表里的每个字典,提取其中_id对应的值存入数组:
states_list = [{'_id': 'CA'}, {'_id': 'TX'}, {'_id': 'FL'}] states = [] for state_dict in states_list: states.append(state_dict['_id']) # 最终结果:['CA', 'TX', 'FL']
2. 列表推导式(更简洁)
用Python列表推导式一行完成提取,代码更紧凑高效:
states_list = [{'_id': 'CA'}, {'_id': 'TX'}, {'_id': 'FL'}] states = [state_dict['_id'] for state_dict in states_list]
3. 容错处理(可选)
如果你的列表里可能存在不含_id键的字典,可以加判断避免报错:
states_list = [{'_id': 'CA'}, {'_id': 'TX'}, {'_id': 'FL'}, {'name': 'NY'}] states = [] for state_dict in states_list: if '_id' in state_dict: states.append(state_dict['_id']) # 最终结果:['CA', 'TX', 'FL']
或者用列表推导式简化带条件的提取:
states = [state_dict['_id'] for state_dict in states_list if '_id' in state_dict]
内容的提问来源于stack exchange,提问作者Skywalker_229
相关产品推荐
相关产品推荐

