I am trying to create a function which generates pairs of users from list. Everyone have to get a pair. Example list of user IDs:
list = [123, 456, 789]
...smth...
result = {123:456, 456:789, 789:123} — OK
list = [123, 456, 789]
...smth...
result = {123:456, 456:123, 789:789} — BAD
list = [123, 456, 789, 234, 678]
...smth...
result = {123:456, 456:123, xxxxx} - BAD
Trying to do this in Python but can't find a solution.
Tried lists, sets, dicts, but cant find an algorithm.
The pairs will be consecutive. I.e. first item with the second, second with the third, and so on, until the last item pairs with the first, and you're showing in your example a dictionary structure, so maybe you can use a function like this.
def make_pairs(input_list):
out_dict = dict() # output dictionary
for i in range(len(input_list)): # i is from 0 to len(list) - 1
# if i is not pointing to the last item
if not i == len(input_list) - 1:
# make pair from the i-th item and the (i+1) item
out_dict[input_list[i]] = input_list[i+1]
# i points to the last item
else:
# make pair from the last item and the first item
out_dict[input_list[i]] = input_list[0]
return out_dict
input_list = [123, 456, 789]
out_dict = make_pairs(input_list)
print(out_dict)
Of course, this is somewhat of a bad solution because not enough information was given and what edge cases might appear. For example, if the list has repeating items, then keys will overwrite each other.
As mentioned above, avoid using list
as a variable name, it's a reserved Python keyword.