Skip to content
Advertisement

Sort lists of dictionaries within dictionary

EDIT:
I’m editing the whole post as it wasn’t as clear as I thougt.

I have this dictionary (list of dictionaries within a dictionary) and I need to sort it by the values of "Position" and "Team", meaning that I need to get all the values from those two keys and print them as I show below. I know how to get each value, but I don’t know how to get them and sort them.

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"} ]
       }

I tried this piece of code, but I still can’t get it to work.

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

My actual dictionary is much bigger than this one, and I pretend to make it even bigger. I need the output to be something like:

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

In this example I only included strings, but I need to also sort similar dictionaries by integer values.

Advertisement

Answer

Extract values of dic as tuple of (Position, Team),
Concatenate them to create flattened tuple of (Position, Team) elements.
Sort them with 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 - Teamn..."
print("n".join(" - ".join(r) for r in res))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement