用Integers替换字典中的键

时间:2018-07-05 18:00:34

标签: python dictionary

my_dict = {k:v for k, v in sorted_freq} # sorted_freq is a list containing key:value. 
{'like': 4870,
'taste': 4508,
'good': 3569,
'flavor': 3449,
'one': 3217,
'product': 3197,
'use': 3165,
'love': 3141,
'great': 3056,
'eat': 1614...}

对于字典中的所有键,如何用从1开始的自然数替换此字典中的键?

 [('like', 4870),
 ('tast', 4508),
 ('good', 3569),
 ('flavor', 3449),
 ('one', 3217),
 ('product', 3197),
 ('use', 3165),
 ('love', 3141),
 ('great', 3056),
 'get', 2400)...]

1 个答案:

答案 0 :(得分:2)

如果从字典开始

您可以尝试在字典理解中使用enumerate,但要注意,字典不适合depending on the version of python进行排序:

{i:v for i,(k,v) in enumerate(my_dict.items(), 1)}

{1: 4870, 2: 4508, 3: 3569, 4: 3449, 5: 3217, 6: 3197, 7: 3165, 8: 3141, 9: 3056, 10: 1614}

如果从元组列表开始(如您刚在编辑中发布的那样):

sorted_freq = [('like', 4870),
 ('tast', 4508),
 ('good', 3569),
 ('flavor', 3449),
 ('one', 3217),
 ('product', 3197),
 ('use', 3165),
 ('love', 3141),
 ('great', 3056),
 ('get', 2400)]


{i:v for i,(k,v) in enumerate(sorted_freq, 1)}