简体   繁体   English

不存在键的情况下字典的排序列表

[英]Sorting list of dictionary in case of key doesn't exist

I have list of dictionary and want to sort by price in ascending order. 我有字典清单,想按价格升序排序。 But few dictionary objects have no price key available to sort. 但是很少有字典对象没有可用的价格键来排序。 I want to move those object to end of the list. 我想将那些对象移到列表的末尾。

I have tried below code 我试过下面的代码

sorted(listObj, key=partial(sort_func, ['price']))

def sort_func(sort_by, listObj):
    fields = []
    for key in sort_by:
        if key in listObj:
            fields.append(listObj[key])
    return fields

And I want to sort below kind of data: 我想对以下数据进行排序:

data = [
        {
           u'errorCode': u'500',
           u'errorMsg': u'Pfffbt. server down.',
        },
        {
           u'errorCode': u'500',
           u'errorMsg': u'Pfffbt. server down.',
        },
        { 
            u'Name': u'United Kingdon',
            u'price': 5222.0,
        },
        {
            u'price': 5237.0,
            u'Name': u'US',
        },
        {
            u'Name': u'General',
            u'price': 5283.0,
        }
    ]

while sorting these data using price ascending order, 5222.0 price should come first instead of errorcode object. 在使用价格升序对这些数据进行排序时,应首先使用5222.0价格而不是errorcode对象。

Note: I don't want to use lambda function because it could have multiple keys with some condition to sort using sort_func So I've to use sort_func anyhow. 注意:我不想使用lambda函数,因为它可能具有多个带有某些条件的键,可以使用sort_func进行排序,因此无论如何我都必须使用sort_func

I found one solution but it is not reliable. 我找到了一种解决方案,但它不可靠。

def sort_func(sort_by, listObj):
    fields = []
    for key in sort_by:
        if key in listObj:
            fields.append(listObj[key])
        else:
            fields.append(99999999999999999999999999) # infinity number
    return fields

Any other suggestion with using sort_func ? 还有其他使用sort_func建议吗?

If you do not want to use lambda , you can try this: 如果您不想使用lambda ,则可以尝试以下操作:

new_data = sorted([i for i in data if "price" in i], reverse=True)+[i for i in data if "errorCode" in i]

Output: 输出:

[{u'price': 5222.0, u'Name': u'United Kingdon'}, {u'price': 5237.0, u'Name': u'US'}, {u'price': 5283.0, u'Name': u'General'}, {u'errorCode': u'500', u'errorMsg': u'Pfffbt. server down.'}, {u'errorCode': u'500', u'errorMsg': u'Pfffbt. server down.'}]

You could add a 'missing_key' counter and increment it for each missing key. 您可以添加一个“ missing_key”计数器,并为每个丢失的键递增计数器。 return a tuple of (missing_keys, fields) and they'll get sorted at the end with the most missing keys going last. 返回一个(missing_keys, fields)元组,它们将在最后排序,最后丢失的键最多。

def sort_func(sort_by, listObj):
    missing_keys = 0
    fields = []
    for key in sort_by:
        if key in listObj:
            fields.append(listObj[key])
        else:
            missing_keys += 1
    return missing_keys, fields

edit: request for detailed explanation 编辑:要求详细说明

tuples(and lists) sort as follows: compare first elements. 元组(和列表)排序如下:比较第一个元素。 If first elements aren't equal, use that comparison, else compare 2nd elements etc.... an empty tuple/list is always less than one with elements. 如果第一个元素相等,则使用该比较,否则比较第二个元素,等等。。。一个空的元组/列表总是少于一个元素。 so: 所以:

lst = [
    (), (10,), (1, []), (2, [10, 11]), (2, [100]), (0, [10, 9, 8]), (0, [11]), (1, [1, 1, 2])
]
print(sorted(lst))

prints: 印刷品:

[
    (),
    (0, [10, 9, 8]),
    (0, [11]),
    (1, []),
    (1, [1, 1, 2]),
    (2, [10, 11]),
    (2, [100]),
    (10,)
]

This sort_func returns a tuple. sort_func返回一个元组。 If the first element (missing_keys) is equal, it's evaluated by the next element (fields). 如果第一个元素(missing_keys)相等,则由下一个元素(字段)求值。 But it first sorts by the number of missing keys. 但是它首先按丢失键的数量排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 如果键不存在,则将键添加到字典列表 - Python add key to list of dictionary if key doesn't exist 如果键不存在,则将字典值映射到列表并返回原始值 - mapping dictionary value to list and return original value if key doesn't exist Python字典中的查找键和默认值(如果键不存在) - Lookup Keys in a Python Dictionary and Default Values if Key doesn't exist 如果文件中不存在某个键的值,请从字典中写入 - write a value of some key from a dictionary if it doesn't exist in the file Python:嵌套字典 - 如果键不存在则创建,否则求和 1 - Python: Nested dictionary - create if key doesn't exist, else sum 1 有没有办法更新 Python 字典的值,但如果它不存在则不添加键? - Is there a way to update the value of a Python dictionary but not add the key if it doesn't exist? 通过创建tuplles的排序列表在python中对字典进行排序不起作用 - Sorting Dictionary in python by making a sorted list of tuplles doesn't work 如果密钥存在,则按键对字典进行排序,如果密钥不存在于列表的末尾 - Sort a dictionary by key if the key exists, if it doesn't put it to the end of the list 循环中,如果不包含键,则仅添加到字典,列表或元组 - in a loop, only add to a dictionary or list or tuple if doesn't contains the key 按键排序字典,然后按值排序(列表或元组?) - Sorting a Dictionary by Key and then Value (list or tuple?)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM