python - 按多个键/值对字典列表进行排序,其中值的顺序应该是特定的

标签 python python-2.7 sorting dictionary lambda

我有一个字典列表,希望每个项目都按特定的属性值排序。

列表:

[
{'name':'alpha', status='run'},
{'name':'alpha', status='in'}, 
{'name':'alpha-32', status='in'},
{'name':'beta', status='out'}
{'name':'gama', status='par'}
{'name':'gama', status='in'}
{'name':'aeta', status='run'}
{'name':'aeta', status='unknown'}
{'pname': 'boc', status='run'}
]

我知道我能做到:

newlist = sorted(init_list, key=lambda k: (k['name'], k['status']) 

但是还有两个条件:

  1. 如果关键字 name 不存在于字典中,则使用与 pname 键对应的值作为名称。
  2. 状态顺序为['out', 'in', 'par', 'run']
  3. 如果 status 值与列表中的内容不一致,请忽略它 - 参见 unknown

结果应该是:

[
{'name':'aeta', status='unknown'}
{'name':'aeta', status='run'}
{'name':'alpha', status='in'},
{'name':'alpha', status='run'},
{'name':'alpha-32', status='in'},
{'name':'beta', status='out'},
{'pname': 'boc', status='run'}
{'name':'gama', status='in'},
{'name':'gama', status='par'}
]

最佳答案

使用

from itertools import count
# Use count() instead of range(4) so that we
# don't need to worry about the length of the status list.

newlist = sorted(init_list,
                 key=lambda k: (k.get('name', k.get('pname')),
                                dict(zip(['out', 'in', 'par', 'run'], count())
                                    ).get(k['status'], -1)
                                )
                )

如果 k['name'] 没有退出,返回到 k['pname'](或者 None 如果 < em>那个不存在)。同样,如果给定状态没有已知整数,则默认为 -1。

我特意将所有内容放在一个逻辑行中,以说明此时您可能只想使用 def 语句定义 key 函数。

def list_order(k):
    name_to_use = k.get('name')
    if name_to_use is None:
        name_to_use = k['pname']  # Here, just assume pname is available

    # Explicit definition; you might still write
    # status_orders = dict(zip(['out', ...], count())),
    # or better yet a dict comprehension like
    # { status: rank for rank, status in enumerate(['out', ...]) }
    status_orders = {
        'out': 0,
        'in': 1,
        'par': 2,
        'run': 3
    }

    status_to_use = status_orders.get(k['status'], -1)

    return name_to_use, status_to_use

newlist = sorted(init_list, key=list_order)

关于python - 按多个键/值对字典列表进行排序,其中值的顺序应该是特定的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564950/

相关文章:

python - 使用 Python 将 VBA 代码解析为更小的代码片段

python - 如何使用 python 修改配置文件?

PHP 以两组为一组对数组进行排序,避免合并具有相同值的项目

javascript - 按字符串值对数组进行排序

python - 根据符号递增数字

python - 如何根据 Pandas DataFrame 中的条件添加每组具有重复值的新列?

Python 正则表达式替换引号中的文本,引号本身除外

Python输入错误: NameError: name 'test' is not defined

python - 如何从非 PyQt 类发出信号?

java - 对 Bean 的 Arraylist 的 Arraylist 进行排序