Python使用orderby库:如何在for循环中打印排序后的列表
Let me break down what's going wrong here and walk you through the fixes:
核心问题:你在遍历JSON字符串,不是排序后的列表
When you run json.dumps(sorted(dic, key=asc('BAIRRO').asc('RUA')), indent=2), it converts your sorted list into a formatted JSON string. So when you put that directly into a for loop, you're iterating over individual characters of the string—not the original list items you intended. That's why it's not working as expected.
正确的做法:先保留排序后的列表,再操作
Here's how to fix this step by step:
Store the sorted list first
Capture the sorted result in a variable before converting it to JSON:sorted_list = sorted(dic, key=asc('BAIRRO').asc('RUA'))Iterate over the list directly
Now you can loop through the actual list items:for item in sorted_list: # Print each item as formatted JSON print(json.dumps(item, indent=2)) # Or just print the item directly if you don't need JSON formatting # print(item)
列表推导式的用法(如果需要预处理)
If you want to pre-generate formatted JSON strings for all items first, you can use a list comprehension:
sorted_list = sorted(dic, key=asc('BAIRRO').asc('RUA')) formatted_json_items = [json.dumps(item, indent=2) for item in sorted_list] # Then iterate and print for json_str in formatted_json_items: print(json_str)
为什么你的初始print语句 worked?
The original print(json.dumps(...)) worked because you were printing the entire JSON string (which represents the sorted list) as a single unit. The indent=2 just made it human-readable, but it was still one big string under the hood.
内容的提问来源于stack exchange,提问作者Shinomoto Asakura

