如何按关键字订购dict并逐行打印



我有这个代码:

def __init__(self, username, password):
self.likesposts = {}
code to fill self.likesposts
top = "{" + "n".join("{!r}: {!r},".format(k, v) for k, v in self.likesposts.items()) + "}"
top = sorted(top)
print(top)

但它不起作用。

self.likesposts中的一行如下:

{'11,821': 'https://www.example.com', '2,449': 'https://www.example.com', '26,153': 'https://www.example.com'}

我怎么能按关键字对这个dict进行排序,但同时每行打印一个"键值对"?

提前谢谢。

编辑:

for key, val in sorted(self.likesposts.items()):
print(f'{key}: {val}')

这一行一行地打印它,但它仍然没有被排序

编辑2:预期输出:

{
'26,153': 'https://www.example.com'
'11,821': 'https://www.example.com',
'2,449': 'https://www.example.com',
}

您必须创建一个新的字典:

d_original = {'2,449': 1, '11,821': 2, '26,153': 3}
sorted_items = sorted(d_original.items(), key=lambda item: int(item[0].replace(',', '')), reverse=True)
# from collections import OrderedDict
# d_new = OrderedDict(sorted_items)
d_new = dict(sorted_items)
for k,v in d_new.items():
print(f'{k}: {v}')

打印:

26,153: 3
11,821: 2
2,449: 1

更新

或者在您的情况下:

sorted_items = sorted(self.likeposts.items(), key=lambda item: int(item[0].replace(',', '')), reverse=True)
self.likeposts = dict(sorted_items)
for k,v in slef.likeposts.items():
print(f'{k}: {v}')

由于Python 3.6的常规dict对象保持插入顺序。如果您正在使用Python 2或Python<3.6,则使用collections.OrderedDict而不是dict

Python中的字典是无序的。如果你想通过排序的密钥访问,你可以这样做:
d = {"a": 4, "c": 10, "b": 11, "d" : 6}  
for key in sorted(d.keys()): 
print(f'{key} {d[key]}')

编辑:

在对字典进行迭代时无法编辑它。因此,将排序后的值存储在新字典中,并覆盖现有字典。

tmp = {}
for key in sorted(d.keys(), key=lambda x: int(x.replace(",",""))): 
tmp[key] = d[key] 
print(f'{key} {d[key]}') 
self.likeposts = tmp

最新更新