【问题标题】:How to reverse the (key,value)'s order of a dict in the output?如何反转输出中字典的(键,值)顺序?
【发布时间】:2020-07-24 06:57:27
【问题描述】:

例如我有这个字典

a = {'Sara': 3, 'Marie': 1, 'James': 1, 'Alex': 1} 我知道我可以用这样的代码一一打印(键,值):

for key,value in a.items():
print(key,value)

结果会是这样的:

Sara 3
Marie 1
James 1
Alex 1

我的问题是如何将此订单保留到:

Alex 1
James 1
Marie 1
Sara 3

【问题讨论】:

标签: python python-3.x dictionary key key-value


【解决方案1】:
for key,value in list(a.items())[::-1]:
    print(key,value)

将 a.items() 转换为列表 然后通过添加[::-1]来切换顺序

【讨论】:

    【解决方案2】:
    a = {'Sara': 3, 'Marie': 1, 'James': 1, 'Alex': 1} 
    sort_a= sorted(a.items(), key=lambda x: x[1], reverse=False)
    for i in sort_a:
       print(i[0],i[1])
    

    试试这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      相关资源
      最近更新 更多