Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python ordereddict when the key is a "numeric string"

i have an unordered dict with numeric keys but in string format, and i want to get a ordered dict (by the numeric key):

my_dict__ = {'3': 6, '1': 8, '11': 2, '7': 55, '22': 1}
my_dict_ = {}
for key, value in my_dict__.items():
    my_dict_[int(key)] = value
my_dict = OrderedDict(sorted(my_dict_.items()))

how can i simply this?

(The result, can have the key as int or string)

Thanks

like image 282
fj123x Avatar asked Mar 22 '23 03:03

fj123x


2 Answers

Something like this:

my_dict = OrderedDict(sorted(my_dict__.items(), key=lambda x:int(x[0])))
# OrderedDict([('1', 8), ('3', 6), ('7', 55), ('11', 2), ('22', 1)])
like image 82
Roman Pekar Avatar answered Apr 01 '23 12:04

Roman Pekar


you can also create the int dict directly with something like:

my_dict = OrderedDict(sorted((int(key), value) for key, value in my_dict__.items()))

this gives you:

OrderedDict([(1, 8), (3, 6), (7, 55), (11, 2), (22, 1)]) 

if that's more useful as an end result.

like image 40
Corley Brigman Avatar answered Apr 01 '23 13:04

Corley Brigman