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

Question:

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]}
Asked By: Akilan M

||

Answers:

You can do this with a list comprehension. This approach will only remove the index based.

In [1]: [{i: List1[:idx]+List1[idx+1:]}for idx, i in enumerate(List1)]
Out[1]: [{1: [2, 3, 4]}, {2: [1, 3, 4]}, {3: [1, 2, 4]}, {4: [1, 2, 3]}]

if you want to remove all occurrences of the list, you can use this,

[{i: list(filter((i).__ne__, List1[:]))}for idx, i in List1]

Execution with string list,

In [2]: [{i: list(filter((i).__ne__, List1[:]))}for idx, i in enumerate(List1)]
Out[2]: 
[{'a': ['b', 'c', 'd']},
 {'b': ['a', 'c', 'd']},
 {'c': ['a', 'b', 'd']},
 {'d': ['a', 'b', 'c']}]
Answered By: Rahul K P

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]}]
Answered By: Andrej Kesely