1

Taking a oldList I thought in compare each Key value, example: T1==T1 take Id, like:

    oldList= [
        {"Id":1, "Key":["T2","T1"]},
        {"Id":2, "Key":["T3","T5"]},
        {"Id":3, "Key":["T2"]},
        {"Id":4, "Key":["T3","T1"]},
        {"Id":5, "Key":["T2","T4"]},
        {"Id":6, "Key":["T2","T1","T3"]},
    ]


for i in lista_2:
    for KeyId in i["Key"]:
        if KeyId == KeyId :
           #grab Id

That's not work, I'm trying to create this resulted:

newList = [
   {"Key":"T1","Ids":[1,4,6]}
   {"Key":"T2", "Ids":[1,3,5]}
   ...
]

In nutshell, I have to say which, T1 has these Ids

Shinomoto Asakura
  • 1,473
  • 7
  • 25
  • 45

1 Answers1

2

Try:

oldList = [
    {"Id": 1, "Key": ["T2", "T1"]},
    {"Id": 2, "Key": ["T3", "T5"]},
    {"Id": 3, "Key": ["T2"]},
    {"Id": 4, "Key": ["T3", "T1"]},
    {"Id": 5, "Key": ["T2", "T4"]},
    {"Id": 6, "Key": ["T2", "T1", "T3"]},
]

out = {}
for d in oldList:
    for k in d["Key"]:
        out.setdefault(k, []).append(d["Id"])

print(out)

Prints:

{"T2": [1, 3, 5, 6], "T1": [1, 4, 6], "T3": [2, 4, 6], "T5": [2], "T4": [5]}

To get the output into format specified in the question:

out = [{"Key": k, "Ids": v} for k, v in out.items()]
print(out)

Prints:

[
    {"Key": "T2", "Ids": [1, 3, 5, 6]},
    {"Key": "T1", "Ids": [1, 4, 6]},
    {"Key": "T3", "Ids": [2, 4, 6]},
    {"Key": "T5", "Ids": [2]},
    {"Key": "T4", "Ids": [5]},
]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91