How to sort a dictionary having keys as a string of numbers in Python

后端 未结 5 1763
攒了一身酷
攒了一身酷 2020-12-10 05:04

I have a dictionary:

a = {\'100\':12,\'6\':5,\'88\':3,\'test\':34, \'67\':7,\'1\':64 }

I want to sort this dictionary with respect to key s

5条回答
  •  盖世英雄少女心
    2020-12-10 05:30

    Dictionaries are unordered. You cannot sort one like you show because the resultant a is a dict, and dicts do not have order.

    If you want, say, a list a list of the keys in sorted order, you can use code like

    >>> def my_key(dict_key):
    ...     try:
    ...         return int(dict_key)
    ...     except ValueError:
    ...         return dict_key
    ...
    >>> sorted(a, key=my_key)
    ['1', '6', '67', '88', '100', 'test']
    

    This relies on the stupid Python behavior that instances of str are always greater than instances of int. (The behaviour is fixed in Python 3.) In an optimal design, the keys of your dict would be things you could compare sanely and you wouldn't mix in strings representing numbers with strings representing words.

    If you want to keep the keys in always-sorted order, you can use the bisect module or implement a mapping that relies on a tree data structure. The bisect module does not accept a key argument like the sorting stuff because this would be potentially inefficient; you would use the decorate–use–undecorate pattern if you chose to use bisect, keeping a sorted list that depends on the result of the key function.

提交回复
热议问题