在Python中对字典排序时出错

在Python中对字典排序时出错,python,Python,当我使用菜单选项1时,我很难将其排序。 我得到以下错误: Traceback (most recent call last): File "C:/Users/willi/PycharmProjects/uscaps.py", line 68, in <module> sort_s(state) File "C:/Users/willi/PycharmProjects/uscaps.py", line 39, in sort_s state =

当我使用菜单选项1时,我很难将其排序。
我得到以下错误:

Traceback (most recent call last):
File "C:/Users/willi/PycharmProjects/uscaps.py", line 68, in <module>
sort_s(state)
File "C:/Users/willi/PycharmProjects/uscaps.py", line 39, in sort_s
state = sort_t(state,0)
File "C:/Users/willi/PycharmProjects/uscaps.py", line 35, in sort_t
tup.sort(key = lambda x: x[key],reverse=rev)
AttributeError: 'dict' object has no attribute 'sort'
我认为我正确地使用了tup对我的听写进行排序

def sort_s(state):
   state = sort_t(state,0)
   print("State    ", " Capital     ", " Flower    ", " Population    "),

  for i in range(0, len(state)):
      print(state[i][0], state[i][1], state[i][2], state[i][3])

 pick = 0

while True:
 #Display Menu to user
  print("**************************************************")
  print("* WELCOME TO THE STATE CAPITAL AND FLOWER MENU   *")
  print("**************************************************")
  print("                                                  ")
print("1. Display All States In Alphabetical Order Along",
      " With Capitals, Population, and Flower ")
print("2. Search for a specific state and display the appropriate Capital",
      "name, State Population, and an image of the associated State Flower")
print("3. Provide a Bar graph of the top 5 populated States showing their",
      "overall population.")
print("4. Update the overall state population for a specific state")
print("5. Exit the program")

try:
    pick = int(input("Enter A Selection 1 - 5: "))
except:
    print("Try Again. Please Pick 1 - 5: ")

if pick == 1:
        sort_s(state)

elif pick == 2:
        state = input ("Enter State Name To Search For: ").lower(),
        url_pic = state_dict_local[state]["URL"]
        response = requests.get(url_pic, stream=True)
        img = Image.open(response.raw)
        img.show()

elif pick == 3:
        display_bar_graph_top5(state)

elif pick == 4:
        state = int("Enter State Name You Want To Update: ").lower(),
        population = int(input( "Please Update the Population: "))
        update(state,state_name,population)

elif pick == 5:
        sys.exit()
else:
        print("Try Again. Please Pick 1 - 5: ")

回溯消息解释得很清楚,
dict
类型没有
排序
属性方法:

>>> dir(dict)
             
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>
>>> 'sort' in dir(dict)
             
False
>>> 'sorted' in dir(dict)
             
False
如果您打算对
词典进行
排序
,则如果:

1-您正在使用Python 3.7+。因此,您可以对
列表(state.items())
进行排序,然后从中创建一个新的
dict

>>> ordered_state = dict(sorted(state.items(), key=lambda x:x[1][key])
2-更早的版本,更好的方法是从
collections
模块订购dict

演示
OrderedDict

>>> from collections import OrderedDict

>>> def sort_states(dictionary, key, rev= False):
        ordered_dict = OrderedDict(sorted(dictionary.items(), key=lambda x: x[1][key]))
        return ordered_dict

             
>>> 
             
>>> ordered_dict_state = sort_states(state, key='Capital')
             
>>> 
             
>>> ordered_dict_state
             
OrderedDict([('Alaska', {'Capital': 'Juneau', 'Bird': 'Willow Ptarmigan', 'Flower': 'Forget Me Not', 'Population': '737438', 'URL': 'https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/primary-     images/Alpineforgetmenot.jpg?itok=VxF44TUl'}), ('Alabama', {'Capital': 'Montgomery', 'Bird': 'Yellowhammer', 'Flower': 'Camellia', 'Population': '4887870', 'URL': 'https://statesymbolsusa.org/sites/statesymbolsusa.org/files/camellia-  flower.jpg'}), ('Arizona', {'Capital': 'Phoenix', 'Bird': 'Cactus Wren', 'Flower': 'Saguaro Cactus Blossom', 'Population': '7171650', 'URL': 'https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/sagua                    roflowersFlickr.jpg?itok=DxWnZav5'})])
>>> 
             
>>> 
             
>>> ordered_dict_state = sort_state(state, key='Population')
             
>>> ordered_dict_state
             
OrderedDict([('Alabama', {'Capital': 'Montgomery', 'Bird': 'Yellowhammer', 'Flower': 'Camellia', 'Population': '4887870', 'URL': 'https://statesymbolsusa.org/sites/statesymbolsusa.org/files/camellia-  flower.jpg'}), ('Arizona', {'Capital': 'Phoenix', 'Bird': 'Cactus Wren', 'Flower': 'Saguaro Cactus Blossom', 'Population': '7171650', 'URL': 'https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/sagua                    roflowersFlickr.jpg?itok=DxWnZav5'}), ('Alaska', {'Capital': 'Juneau', 'Bird': 'Willow Ptarmigan', 'Flower': 'Forget Me Not', 'Population': '737438', 'URL': 'https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/primary-     images/Alpineforgetmenot.jpg?itok=VxF44TUl'})])
>>> 

更正

  • 字典没有排序方法
  • 通过对dict.items()进行排序对字典进行排序
  • 将已排序的项转换回字典(因为Python现在根据插入顺序维护字典中的项)
  • 清理打印结果
代码

state = {"Alabama": {"Capital": "Montgomery", "Bird": "Yellowhammer",
                      "Flower": "Camellia",
                      "Population": "4887870",
                      "URL": "https://statesymbolsusa.org/sites/statesymbolsusa.org/files/camellia- flower.jpg"},
          "Alaska": {"Capital": "Juneau", "Bird": "Willow Ptarmigan",
                     "Flower": "Forget Me Not",
                     "Population": "737438",
                      "URL":  
    "https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/primary-images/Alpineforgetmenot.jpg?itok=VxF44TUl"},
          "Arizona": {"Capital": "Phoenix", "Bird": "Cactus Wren",
                      "Flower": "Saguaro Cactus Blossom",
                      "Population": "7171650",
                      "URL": 
                 "https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/saguaroflowersFlickr.jpg?itok=DxWnZav5"},


     }

def sort_t(tup,key, rev= False):
    # We sort name value pairs of (i.e. tup.items())
    # Convert sorted pairs back to dictionary
    return {k:v for k, v in sorted(tup.items(), key = lambda kv: kv[0], reverse = rev)}
    
def sort_s(state):
    # Sort by state
    state = sort_t(state, False)
    
    # Header (fixed width fields)
    print('{:<10} {:<15} {:<25} {:<15}'.format("State", "Capital", "Flower", "Population"))

    # Values (fixed width fields)
    for st, v in state.items():
        # v is the nested dictionary with state information
        print(f'{st:<10} {v["Capital"]:<15} {v["Flower"]:<25} {v["Population"]:<15}')

while True:
    #Display Menu to user
    print('''
      **************************************************
      * WELCOME TO THE STATE CAPITAL AND FLOWER MENU   *
      **************************************************
      
      1. Display All States In Alphabetical Order Along,
      " With Capitals, Population, and Flower ")
      2. Search for a specific state and display the appropriate Capital,
      "name, State Population, and an image of the associated State Flower
      3. Provide a Bar graph of the top 5 populated States showing their
       overall population.
      4. Update the overall state population for a specific state
      5. Exit the program
      ''')

    try:
        pick = int(input("Enter A Selection 1 - 5: "))
    except:
        print("Try Again. Please Pick 1 - 5: ")
        continue

    if pick == 1:
            sort_s(state)

    elif pick == 2:
            state = input ("Enter State Name To Search For: ").lower(),
            url_pic = state_dict_local[state]["URL"]
            response = requests.get(url_pic, stream=True)
            img = Image.open(response.raw)
            img.show()

    elif pick == 3:
            display_bar_graph_top5(state)

    elif pick == 4:
            state = int("Enter State Name You Want To Update: ").lower(),
            population = int(input( "Please Update the Population: "))
            update(state,state_name,population)

    elif pick == 5:
            sys.exit()
    else:
            print("Try Again. Please Pick 1 - 5: ")

您希望输出的格式是什么?您能举一个所需输出的例子吗?谢谢您与我们分享详细信息,这当然很有帮助。但你的问题还没有精简到最低限度@goalie1998它应该按字母顺序打印所有州。
print(sorted(state))
将按字母顺序打印州名列表。@goalie1998如果我添加大写字母、人口和花卉,它也会打印吗?我需要新的排序方法吗?@WilliamHoward,请参阅更新answer@DarryIG谢谢,我知道我在哪儿了。谢谢你的邀请help@WilliamHoward--很高兴它有用。
state = {"Alabama": {"Capital": "Montgomery", "Bird": "Yellowhammer",
                      "Flower": "Camellia",
                      "Population": "4887870",
                      "URL": "https://statesymbolsusa.org/sites/statesymbolsusa.org/files/camellia- flower.jpg"},
          "Alaska": {"Capital": "Juneau", "Bird": "Willow Ptarmigan",
                     "Flower": "Forget Me Not",
                     "Population": "737438",
                      "URL":  
    "https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/primary-images/Alpineforgetmenot.jpg?itok=VxF44TUl"},
          "Arizona": {"Capital": "Phoenix", "Bird": "Cactus Wren",
                      "Flower": "Saguaro Cactus Blossom",
                      "Population": "7171650",
                      "URL": 
                 "https://statesymbolsusa.org/sites/statesymbolsusa.org/files/styles/public/saguaroflowersFlickr.jpg?itok=DxWnZav5"},


     }

def sort_t(tup,key, rev= False):
    # We sort name value pairs of (i.e. tup.items())
    # Convert sorted pairs back to dictionary
    return {k:v for k, v in sorted(tup.items(), key = lambda kv: kv[0], reverse = rev)}
    
def sort_s(state):
    # Sort by state
    state = sort_t(state, False)
    
    # Header (fixed width fields)
    print('{:<10} {:<15} {:<25} {:<15}'.format("State", "Capital", "Flower", "Population"))

    # Values (fixed width fields)
    for st, v in state.items():
        # v is the nested dictionary with state information
        print(f'{st:<10} {v["Capital"]:<15} {v["Flower"]:<25} {v["Population"]:<15}')

while True:
    #Display Menu to user
    print('''
      **************************************************
      * WELCOME TO THE STATE CAPITAL AND FLOWER MENU   *
      **************************************************
      
      1. Display All States In Alphabetical Order Along,
      " With Capitals, Population, and Flower ")
      2. Search for a specific state and display the appropriate Capital,
      "name, State Population, and an image of the associated State Flower
      3. Provide a Bar graph of the top 5 populated States showing their
       overall population.
      4. Update the overall state population for a specific state
      5. Exit the program
      ''')

    try:
        pick = int(input("Enter A Selection 1 - 5: "))
    except:
        print("Try Again. Please Pick 1 - 5: ")
        continue

    if pick == 1:
            sort_s(state)

    elif pick == 2:
            state = input ("Enter State Name To Search For: ").lower(),
            url_pic = state_dict_local[state]["URL"]
            response = requests.get(url_pic, stream=True)
            img = Image.open(response.raw)
            img.show()

    elif pick == 3:
            display_bar_graph_top5(state)

    elif pick == 4:
            state = int("Enter State Name You Want To Update: ").lower(),
            population = int(input( "Please Update the Population: "))
            update(state,state_name,population)

    elif pick == 5:
            sys.exit()
    else:
            print("Try Again. Please Pick 1 - 5: ")
      **************************************************
      * WELCOME TO THE STATE CAPITAL AND FLOWER MENU   *
      **************************************************
      
      1. Display All States In Alphabetical Order Along,
      " With Capitals, Population, and Flower ")
      2. Search for a specific state and display the appropriate Capital,
      "name, State Population, and an image of the associated State Flower
      3. Provide a Bar graph of the top 5 populated States showing their
       overall population.
      4. Update the overall state population for a specific state
      5. Exit the program
      
Enter A Selection 1 - 5: 1
State      Capital         Flower                    Population     
Alabama    Montgomery      Camellia                  4887870        
Alaska     Juneau          Forget Me Not             737438         
Arizona    Phoenix         Saguaro Cactus Blossom    7171650