如何用嵌套for循环访问字典值?现有代码输出异常求解
问题与解决方案
需求与现有问题
拥有如下嵌套字典:
service_dict = { 'Other': [('Waxing', 20), ('Manicure', 30), ('Extensions', 35)], 'Styling': [('Blow Dry', 15), ('Perm', 25), ('Straightening', 25)], 'Color': [('Full Color', 40), ('Color Retouch', 20), ('Highlights', 30)], 'Haircut': [("Men's Cut", 20), ("Womens's Cut", 20), ("Children's Cut", 10), ('Specialty Cut', 30)] }
希望按顺序输出所有元素:Other、Waxing、20、Manicure、30……
当前使用的代码:
for key, value in dict.items(): print(key) for i in range(0, len(value)): print(value[i]) for j in range(1): print(value[i][j])
实际输出:
Other ('Waxing', 20) Waxing ('Manicure', 30) Manicure ...
疑问:最后一层循环为何无法同时打印Waxing和20,预期该循环能输出元组里的两个元素。
问题原因
- 最后一层循环
for j in range(1)仅会执行一次——range(1)生成的序列是[0],所以只能取到元组中索引为0的元素(服务名称),拿不到索引1的价格。 - 代码中多了一行
print(value[i]),会把整个元组(比如('Waxing', 20))打印出来,这是多余的。
修正后的代码
直接遍历每个元组内的元素,写法更简洁直观:
service_dict = { 'Other': [('Waxing', 20), ('Manicure', 30), ('Extensions', 35)], 'Styling': [('Blow Dry', 15), ('Perm', 25), ('Straightening', 25)], 'Color': [('Full Color', 40), ('Color Retouch', 20), ('Highlights', 30)], 'Haircut': [("Men's Cut", 20), ("Womens's Cut", 20), ("Children's Cut", 10), ('Specialty Cut', 30)] } for category, services in service_dict.items(): print(category) for service_name, price in services: print(service_name) print(price)
如果坚持用索引遍历的写法,修改如下:
service_dict = { 'Other': [('Waxing', 20), ('Manicure', 30), ('Extensions', 35)], 'Styling': [('Blow Dry', 15), ('Perm', 25), ('Straightening', 25)], 'Color': [('Full Color', 40), ('Color Retouch', 20), ('Highlights', 30)], 'Haircut': [("Men's Cut", 20), ("Womens's Cut", 20), ("Children's Cut", 10), ('Specialty Cut', 30)] } for key, value in service_dict.items(): print(key) for i in range(len(value)): # 去掉打印整个元组的行 for j in range(2): # 改成range(2),覆盖索引0和1 print(value[i][j])
预期输出
Other Waxing 20 Manicure 30 Extensions 35 Styling Blow Dry 15 Perm 25 Straightening 25 Color Full Color 40 Color Retouch 20 Highlights 30 Haircut Men's Cut 20 Womens's Cut 20 Children's Cut 10 Specialty Cut 30
内容的提问来源于stack exchange,提问作者jrdaz14
相关产品推荐
相关产品推荐

