You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm不识别字典sort方法但在线Playground可用,报错求替代方案

Fixing the 'dict_items' has no attribute 'sort' Error in Python

Hey there! Let's break down why you're hitting this error and how to fix it smoothly.

The Root Cause

When you call my_dict.items() in Python, it returns a dict_items object—this is a dynamic view object that mirrors changes to the original dictionary, not a static list. Unlike lists, view objects don't come with a built-in sort() method, which is exactly why PyCharm throws that AttributeError.

As for why it works in the web playground? Chances are the environment is implicitly converting the dict_items to a list behind the scenes, or you might have accidentally used a list conversion there without noticing.

Solutions to Replace the Sort Functionality

Here are two straightforward, reliable ways to get sorted dictionary items:

1. Convert to a List First, Then Use sort()

If you want to sort the items in-place (modify the list directly), convert the dict_items to a list first:

# Example dictionary
my_dict = {"banana": 3, "apple": 1, "cherry": 2}

# Convert dict_items to a mutable list
items_list = list(my_dict.items())

# Sort by key (default behavior)
items_list.sort()
print(items_list)  # Output: [('apple', 1), ('banana', 3), ('cherry', 2)]

# Or sort by value using a lambda as the key
items_list.sort(key=lambda x: x[1])
print(items_list)  # Output: [('apple', 1), ('cherry', 2), ('banana', 3)]

2. Use the sorted() Function (Recommended)

The sorted() function is cleaner and more flexible—it accepts any iterable (including dict_items) and returns a new sorted list directly, no extra conversion step needed:

# Sort by key
sorted_by_key = sorted(my_dict.items())

# Sort by value
sorted_by_value = sorted(my_dict.items(), key=lambda x: x[1])

# Reverse the sort order
reverse_sorted = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)

Quick Recap

  • Never call sort() directly on dict_items—it's not supported for view objects.
  • Use list(my_dict.items()).sort() if you want to sort in-place, or sorted(my_dict.items()) for a new sorted list.
  • Use the key parameter to customize sorting logic (e.g., by value, key length, or custom criteria).

内容的提问来源于stack exchange,提问作者Uta Cho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:28:39