【问题标题】:How to order a dictionary based on the keys? [duplicate]如何根据键订购字典? [复制]
【发布时间】:2021-05-23 17:27:23
【问题描述】:

我有一个字典,其中表示项目的键和值表示该项目的计数。 例如在下面的字典中:

dict= {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1}

'11' occurred 4 times
'0' occurred 2 times
'65' occurred 1 time

dict.keys() 是降序还是升序的字典如何排序?

理想的输出将是

dict={'0':2,'11':4,'12':1,'13':1,'65':1,'88':1} 

dict={'88':1,'65':1,'13':1,'12':1,'11':4,'0':2}

任何帮助将不胜感激

【问题讨论】:

标签: python python-3.x dictionary


【解决方案1】:

注意:不要使用dict 作为变量名,因为它已经是一个内置函数。

your_dict = {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1} 更好。

您可以使用sample_list = list(your_dict.items()) 将给定的字典转换成一个列表。

在 Python 字典中,items() 方法用于返回包含所有字典键和值的列表。

使用sample_list.sort() 对列表进行排序。

要反转列表,请使用reverse = True

sample_list = list(your_dict.items())
sample_list.sort(reverse = True)

然后使用dict = dict(sample_list)将其转换为字典并打印出来。

【讨论】:

    【解决方案2】:

    score = {'eng': 33, 'sci': 85, 'math': 60}

    你可以这样做......

    score_sorted = sorted(score.items(), key=lambda x:x[0])

    如果你想按 val 排序,那么score_sorted = sorted(score.items(), key=lambda x:x[1])。您也可以添加 reverse=True 来更改顺序。

    【讨论】:

    • 我们需要调用 dict(score_sorted) 以便将元组转换回字典。另外,@Pytan,如果我们只是按密钥排序,我认为我们不需要传递密钥,因为我相信这是默认设置。
    【解决方案3】:
    myDict= {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1}
    sortDict = {}
    
    for i in sorted(myDict.keys()) :  
         sortDict[i] = myDict[i]
    
    print(sortDict) 
    

    【讨论】:

      【解决方案4】:

      与旧帖子相反,自 CPython 3.6(非官方,作为 C 实现细节)和 Python 3.7(官方)以来,字典不再是无序的并且可以排序。

      要按键排序,请使用字典推导按所需顺序构建新字典。如果要按字符串排序顺序排序,请使用以下命令,但请注意 '2' 作为字符串位于 '11' 之后:

      >>> d = {'11': 4, '2': 2, '65': 1, '88': 1, '12': 1, '13': 1}
      >>> {k:d[k] for k in sorted(d)}
      {'11': 4, '12': 1, '13': 1, '2': 2, '65': 1, '88': 1}
      

      要按整数值排序,请传递一个将字符串转换为整数的键函数:

      >>> {k:d[k] for k in sorted(d,key=lambda x: int(x))}
      {'2': 2, '11': 4, '12': 1, '13': 1, '65': 1, '88': 1}
      

      或者相反,你可以使用reverse=True 或者只是否定整数:

      >>> {k:d[k] for k in sorted(d,key=lambda x: -int(x))}
      {'88': 1, '65': 1, '13': 1, '12': 1, '11': 4, '2': 2}
      

      对于较旧的 Python 版本,将字典转换为带有 list(d.items()) 的列表并使用类似的排序。

      【讨论】:

        【解决方案5】:
        dict= {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1}
        

        你可以试试这样的字典理解

        sorted_dict={k:dict[k] for k in sorted(dict)}
        print(sorted_dict)
        

        【讨论】:

          猜你喜欢
          • 2011-05-15
          • 1970-01-01
          • 2022-11-13
          • 2012-05-10
          • 1970-01-01
          • 1970-01-01
          • 2021-09-28
          • 2011-11-07
          • 2019-03-18
          相关资源
          最近更新 更多