【问题标题】:Sort lists of dictionaries within dictionary对字典中的字典列表进行排序
【发布时间】:2020-07-12 00:15:03
【问题描述】:

编辑:
我正在编辑整个帖子,因为它没有我想的那么清楚。

我有这本字典(字典中的字典列表),我需要按 "Position""Team" 的值对其进行排序,这意味着我需要从这两个键中获取所有值并将它们打印为我在下面展示。我知道如何获取每个值,但我不知道如何获取它们并对其进行排序。

dic = {"Racing" : [ {"Team" : "Racing",
                     "Player" : "Player 1",
                     "Position" : "GK" },
                    {"Team" : "Racing",
                     "Player" : "Player 2",
                     "Position" : "DF"} ],
       "Independiente" : [ {"Team" : "Independiente",
                            "Player" : "Player A",
                            "Position" : "GK"},
                           {"Team" : "Independiente",
                            "Player" : "Player B",
                            "Position" : "DF"} ]
       }

我尝试了这段代码,但我仍然无法让它工作。

{k: v for k, v in sorted(dic.items(), key=lambda item: (item[1][2], item[1][0]))}

我的实际字典比这本大得多,我假装让它变得更大。我需要输出类似于:

DF - Independiente
DF - Racing
GK - Independiente
GK - Racing

在这个例子中,我只包含了字符串,但我还需要按整数值对相似的字典进行排序。

【问题讨论】:

  • 我相信有人会给你一个很好的答案,看看做一些递归。 :)
  • 当你说按职位和团队时,你想要职位的字典排序吗?
  • 我将编辑以澄清我的问题。
  • 请也显示您想要的结果。
  • 不清楚你想要什么。您是否希望它在dic 本身内部进行排序,或者您想要一个新的字典列表。您正在尝试创建具有多个相同键的字典,这是不可能的。

标签: python list sorting dictionary


【解决方案1】:

将 dic 的值提取为 (Position, Team) 的元组,
连接它们以创建扁平化的 (Position, Team) 元素元组。
用 sorted 对它们进行排序

dic = {"Racing" : [ {"Team" : "Racing",
                     "Player" : "Player 1",
                     "Position" : "GK" },
                    {"Team" : "Racing",
                     "Player" : "Player 2",
                     "Position" : "DF"} ],
       "Independiente" : [ {"Team" : "Independiente",
                            "Player" : "Player A",
                            "Position" : "GK"},
                           {"Team" : "Independiente",
                            "Player" : "Player B",
                            "Position" : "DF"} ]
       }

res = ()
#           emit as tuple of (Position, Team) from all of dic's values
for PT in ( tuple((team['Position'], team['Team']) for team in v) for v in dic.values() ):
    res = res + PT
    # concatenate all tuples to flatten into one large tuple
res = sorted(res)
# sort tuple of (Position, Team) values

print(res)

# create string representation in format "Position - Team\n..."
print("\n".join(" - ".join(r) for r in res))

【讨论】:

  • 这正是我想要的。看来我的帖子并没有其他人说的那么不清楚!为了简洁起见,我实际上简化了我的问题,但在我的程序中,我使用两个组合框来选择 CSV 文件的字段以对文本框中的输出进行排序。所以,在运行应用程序时,我真的不知道排序字段。它们是从 CSV 文件中检索的,我构建了程序来获取几乎任何 CSV 文件。此代码完美运行!我只是对其进行了调整以从组合中获取排序字段。非常感谢!
【解决方案2】:

我找到的一个解决方案是使用辅助字典,您可以在其中保存团队的位置。然后在输出数据时按团队和位置排序。例如:

from collections import defaultdict

dic = {"Racing" : [ {"Team" : "Racing",
                     "Player" : "Player 1",
                     "Position" : "GK" },
                    {"Team" : "Racing",
                     "Player" : "Player 2",
                     "Position" : "DF"} ],
       "Independiente" : [ {"Team" : "Independiente",
                            "Player" : "Player A",
                            "Position" : "GK"},
                           {"Team" : "Independiente",
                            "Player" : "Player B",
                            "Position" : "DF"} ]
       }
       
dict = defaultdict(list)
for team in dic:
    for player in dic[team]:
        dict[player["Position"]].append(player["Team"])
for position in sorted(dict.keys()):
    for item in sorted(dict[position]):
        print(f"{position} - {item}")

输出:

DF - Independiente
DF - Racing
GK - Independiente
GK - Racing

【讨论】:

    【解决方案3】:

    我不确定您所说的“按职位和团队排序”是什么意思,请写下您为输出编写的内容。

    如果你希望你的输出是......

    DF - Independiente
    DF - Racing
    GK - Independiente
    GK - Racing  
    

    然后你想要这个,存储但是你想存储它。可能在列表或新字典中。

    for i in dic.values():
        print(list(i[1].values())[2]+' - '+list(i[1].values())[0])
        print(list(i[1].values())[2]+' - '+list(i[0].values())[0])
    

    【讨论】:

      猜你喜欢
      • 2011-02-22
      • 2014-02-14
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      相关资源
      最近更新 更多