Sorting a list of dictionaries by a specific dictionary key

This question already has an answer here:

  • How do I sort a list of dictionaries by values of the dictionary in Python? 17 answers

  • 您可以使用key参数sorted

    array = sorted(array,key= lambda x: x['d'])
    

    Since you have to use your own sorting code, most answers on this site won't help you --- they're generally based on the sort or sorted functions that come with Python.

    You can sort these dictionaries using a slight variant of whatever sorting function you already have. Wherever your old code compares two items like:

    if a < b:
        # swap a and b
    

    ...you'll instead compare values contained in those items:

    attribute = 'Race Time'
    if a[attribute] < b[attribute]:
        # swap a and b
    

    Note that your "race times" are actually strings in some weird format that will require work to convert into comparable numbers. This will probably be worth writing as a separate function, which your sorting function would use in exactly the same places:

    if race_time(a) < race_time(b):
        ...
    

    ...or even:

    if is_faster(a, b):
        ...
    

    For a more general solution, look up comparator functions , which most languages use for general-purpose sorting, and key functions , a more efficient variant used in modern versions of Python. ("How do I sort a list of dictionaries by values of the dictionary in Python?", mentioned by SuperBiasedMan in the comments, has many examples of using key functions.)

    链接地址: http://www.djcxy.com/p/70778.html

    上一篇: 在Python中的列表中排序嵌套的字典?

    下一篇: 按特定字典键对字典列表进行排序