Python查询嵌套dictionary与list中指定key-value的方法
原有代码错误原因
- 直接触发AttributeError的原因:
data['gems']是列表类型,不存在.items()方法,在循环中对列表直接调用nest.items()必然报错。 - 遍历逻辑错误:循环取到索引
x后,没有获取列表中对应位置的字典元素,就算要遍历键值对,也应该取nest[x]这个单条字典再调用.items(),而非对整个列表操作。 - 判断逻辑无效:代码中
nest.items() == ("colour", "yellow")只是一行孤立的比较表达式,既没有做条件分支判断,也没有筛选符合要求的元素,完全不生效。 - 列表赋值错误:初始定义的
location是空列表,直接通过location[x] = [x]给指定索引赋值会触发索引越界,空列表追加元素需要用append()方法。 - 逻辑缺失:就算位置存储逻辑正常,代码也没有进一步根据位置取对应的
month字段,无法实现最初的查询目标。
正确实现方案
不需要单独存位置再二次查询,直接遍历列表匹配目标字段、收集对应月份即可,逻辑更简洁。
基础版本:指定colour查询对应月份
data = {'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'}, {'name': 'amethyst', 'colour': 'purple', 'month': 'February'}, {'name': 'bloodstone', 'colour': 'green/red', 'month': 'March'}, {'name': 'diamond', 'colour': 'clear', 'month': 'April'}, {'name': 'emerald', 'colour': 'green', 'month': 'May'}, {'name': "cat's eye", 'colour': 'yellow', 'month': 'June'}, {'name': 'turquoise', 'colour': 'turquoise', 'month': 'July'}, {'name': 'sardonyx', 'colour': 'red', 'month': 'August'}, {'name': 'peridot', 'colour': 'green', 'month': 'September'}, {'name': 'opal', 'colour': 'iridescent', 'month': 'October'}, {'name': 'topaz', 'colour': 'yellow', 'month': 'November'}, {'name': 'ruby', 'colour': 'red', 'month': 'December'}]} target_colour = "yellow" match_months = [] for gem_info in data['gems']: if gem_info['colour'] == target_colour: match_months.append(gem_info['month']) print(match_months) # 输出结果:['June', 'November']
注:同一个属性值可能对应多个月份,比如
yellow对应六月、十一月,red对应一月、八月、十二月,因此用列表存储所有匹配结果更严谨,如果确定只有一个匹配项,直接取列表第一个元素即可。
通用版本:支持按name或colour任意字段查询
封装成可复用的函数,传入要查询的字段和值即可返回结果:
def query_month(query_field, query_value, dataset): result = [] for item in dataset['gems']: # 用get取字段避免字段不存在时报错 if item.get(query_field) == query_value: result.append(item['month']) return result # 示例1:按name查询ruby对应的月份 print(query_month('name', 'ruby', data)) # 输出:['December'] # 示例2:按colour查询green对应的月份 print(query_month('colour', 'green', data)) # 输出:['May', 'September']
内容的提问来源于stack exchange,提问作者Jas
相关产品推荐
相关产品推荐

