Home > Blockchain >  Possible combination of a list to key value pairs keeping 1 element as key and rest as a value
Possible combination of a list to key value pairs keeping 1 element as key and rest as a value

Time:10-14

Hi can someone help me with the below requirement ? Please note the list length can be any number , for example i have just put 4.

I need the output as list of dictionaries with 1 value as key and rest of the values clubbed as list of all possible combination.

Thanks in advance.

Input:

List1 = [1,2,3,4]

Output:

List2 = [ {1:[2,3,4]},{2:[1,3,4]},{3:[1,2,4]} ,{4:[1,2,3]}

CodePudding user response:

Try:

List1 = [1, 2, 3, 4]

out = [
    {v: [v for idx2, v in enumerate(List1) if idx != idx2]}
    for idx, v in enumerate(List1)
]
print(out)

Prints:

[{1: [2, 3, 4]}, {2: [1, 3, 4]}, {3: [1, 2, 4]}, {4: [1, 2, 3]}]

CodePudding user response:

You can do this with list comprehension,

In [1]: [{i 1: [j for j in List1 if j != i 1]} for i in range(len(List1))]
Out[1]: [{1: [2, 3, 4]}, {2: [1, 3, 4]}, {3: [1, 2, 4]}, {4: [1, 2, 3]}]
  • Related