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
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)])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With