I have a dictionary with string-type keys and float-type values. I sort the dictionary by the value in descending order and wang to print the v=keys and values;
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]
the sample for keys and values:
,_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
I want to print 20 samples from the dictionary, but I don't know how to code if several keys have the same values, keys are additionally sorted lexicographically.
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
Thanks