打印字典中的键和值 indeending,并且需要按字典顺序额外排序相同的值



我有一个字典,里面有字符串类型的键和浮点类型的值。我按照值的降序对字典进行排序,王打印v=键和值;

sum_count = sum(character_dist.values())
character_dist_2 = {k: v/sum_count for k,v in character_dist.items()}
sorted_dict = {}
sorted_keys = sorted(character_dist_2, key=character_dist_2.get,reverse=True)  # [1, 3, 2]
for w in sorted_keys:
sorted_dict[w] = character_dist_2[w]

密钥和值的示例:

,_and_ 0.0029020624
_that_ 0.0020209420
_with_ 0.0016136799
n_the_ 0.0014651189
_and_t 0.0013601016
d_the_ 0.0011884881
_of_th 0.0011859267
and_th 0.0011167690
nd_the 0.0011065234
_they_ 0.0010424884
of_the 0.0010143131
e_was_ 0.0010143131
_and_s 0.0009886991
t_the_ 0.0009554010
_the_s 0.0009528396
f_the_ 0.0009374712
_in_th 0.0008964888
in_the 0.0008426995

我想从字典中打印20个样本,但我不知道如何编码。如果几个键的值相同,则会按照字典对键进行额外排序。

L = 20
original_N = L
for key, value in sorted_dict.items():
# this is the part I don't know
if L !=0:
print("% s %.10f" %(key, value))
L = L-1

感谢

您可以将字典键和值排序在一起,并使用它们直接形成新字典:

sorted_dict = dict(sorted(character_dist_2.items(),key=lambda kv:(-kv[1],kv[0])))

这里的排序键是一个将负值与键组合在一起的元组。这将使值按降序排序,对于相同的值,键按升序排序。

示例:

character_dist   = {"gg": 1, "hh": 2, "tt": 2, "qq":3, "ww": 4, "oo":5, "pp": 6}
sum_count        = sum(character_dist.values())
character_dist_2 = {k: v/sum_count for k,v in character_dist.items()}
sorted_dict = dict(sorted(character_dist_2.items(),key=lambda kv:(-kv[1],kv[0])))
print(sorted_dict)
{'pp': 0.2608695652173913,   # values in descending order
'oo': 0.21739130434782608, 
'ww': 0.17391304347826086, 
'qq': 0.13043478260869565, 
'hh': 0.08695652173913043,  # same value,  
'tt': 0.08695652173913043,  # lexicographic order
'gg': 0.043478260869565216}

最新更新