【问题标题】:Custom sort list of dictionaries by other dictionary or list按其他字典或列表自定义字典排序列表
【发布时间】:2020-08-04 18:42:18
【问题描述】:

我有一个字典列表,我想根据外部排序(列表、字典、任何有效的)进行排序。假设我有以下列表:

list_a = [{"dylan": "alice"}, {"arnie": "charles"}, {"chelsea": "bob"}]

我想这样排序

sorted_list_a = [{"arnie": "charles"}, {"chelsea": "bob"}, {"dylan": "alice"}]

我试过这样做:

# list_a will have a variable number of dictionaries all with unique keys
# list_order will have all dictionary keys ordered, even if they don't appear in list_a
list_order = [{"arnie": 1}, {"britta": 2}, {"chelsea": 3}, {"dylan": 4}]
list_a.sort(key=lambda x: list_order[x.keys()])

但我得到TypeError: list indices must be integers or slices, not dict_keys。我觉得我已经接近了,但我还不能走到最后。

【问题讨论】:

  • 您的问题是“给定一个键值对x 作为字典,我如何获取键?”?
  • @Asocia 如果有多个键怎么办?
  • @deadshot 我专门要求只提供一个键值对,但没关系,我想通了,哈哈:D

标签: python python-3.x list sorting dictionary


【解决方案1】:

试试这个:

def fun(x):
    k, = (x)
    for d in list_order:
        if k in d:
            return d[k]

res = sorted(list_a, key=fun)
print(res)

输出:

[{'arnie': 'charles'}, {'chelsea': 'bob'}, {'dylan': 'alice'}]

【讨论】:

    【解决方案2】:
      l = [{"dylan": "alice"}, {"arnie": "charles"}, {"chelsea": "bob"}]
    d={}
    for i in l:
        for x,y in (i.items()):
           d[x]=y
    print(sorted(d.items(),key=lambda x: x[0]))
    

    【讨论】:

    • 您忽略了要排序的列表 (list_a)。
    • 已编辑,请检查输出,如果看起来不错,请点赞
    • 现在是来自list_a的数据,错误地称为list_order,而忽略了来自真实list_order的数据。你在开玩笑吧? :-)
    • 我还没有看到列表名称,我看到了输出 sorted_list_a = [{"arnie": "charles"}, {"chelsea": "bob"}, {"dylan": "alice"} ] 并将其与我的输出匹配
    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2011-02-22
    • 1970-01-01
    • 2011-09-23
    相关资源
    最近更新 更多