-1
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...}

How do I replace the Key in this dictionary by natural numbers starting from 1 for all the Keys in dictionary?

 [('like', 4870),
 ('tast', 4508),
 ('good', 3569),
 ('flavor', 3449),
 ('one', 3217),
 ('product', 3197),
 ('use', 3165),
 ('love', 3141),
 ('great', 3056),
 'get', 2400)...]
  • 1
    How do you know how to order these numbers? Dictionaries are not sorted in all versions of python – user3483203 Jul 05 '18 at 18:01
  • can you show us what did you try and what error you are getting? – Nagashayan Jul 05 '18 at 18:02
  • Dictionaries are not ordered! If you just want integers from a start range to an end range without worrying what their values are, we can help. – imperialgendarme Jul 05 '18 at 18:02
  • 1
    @patrickhaugh I disagree with that duplicate. It's too much of a leap to apply to this problem. It doesn't even apply to dictionaries. – roganjosh Jul 05 '18 at 18:04
  • Can you tell me how to replace the 'Key' to integers such as 1, 2, 3,... ? – Dhruv Bhardwaj Jul 05 '18 at 18:04
  • 1
    Instead of replacing the key in the dictionary, *create* the dictionary using `enumerate` with your sorted list. That way, even though the dictionary will not be ordered, the numbers will be. – user3483203 Jul 05 '18 at 18:05
  • 1
    @roganjosh I disagree. I think the solution sought after here is the creation of a dict `{i: v for i, (k, v) in enumerate(sorted_freq, 1)}`, and the only part of that missing from the code in the question is `enumerate` – Patrick Haugh Jul 05 '18 at 18:11
  • @patrickhaugh but as a direct dupe it ignores the order issues inherent to dictionaries. I'm just not sure the logical link is so clear for someone who might stumble over this question, since they probably wouldn't be searching this problem if they have the necessary understanding in the first place. – roganjosh Jul 05 '18 at 18:17

1 Answers1

2

If starting from a dictionary:

You can try using enumerate in a dictionary comprehension, but be aware that dictionaries are not garanteed to be ordered 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}

If Starting from a list of tuples (as you just posted in your edit):

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)}
sacuL
  • 42,057
  • 8
  • 58
  • 83