Python – Add list values to dictionary but ensure they are not consecutive
Hello. I’ve got a list, say :
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
I’ve also got a dictionary with 3 keys with empty lists, say :
sample = {
"A": [],
"B": [],
"C": [],
}
I need to insert the values of the list into the values of the dictionary, but ensure that each key only has 4 values, and they cannot be consecutive.
For example, this would be correct, since each key has 4 values and none of them are consecutive :
sample = {
"A": [1, 3, 5, 7],
"B": [2, 10, 12, 8],
"C": [4, 11, 9, 6],
}
The values can be random (that is, they need not be in ascending/descending order), but they have to be from the list. Can someone please help me on this?
This is what I’ve got so far. It inserts the values into the list, but the values are all consecutive.
`overs = []
# Creates a list with values from 1 to 12
for i in range(1, 13):
overs.append(i)
print(overs)
players = {"A": [], "B": [], "C": []}
# Creates a dictionary where the values of the list are inserted into the values of the dictionary
for player in players:
for i in range(1, 13):
try:
if len(players[player]) < 4:
players[player].append(overs[0])
overs.pop(0)
except IndexError:
break
print(players)`
Output :
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
{'A': [1, 2, 3, 4], 'B': [5, 6, 7, 8], 'C': [9, 10, 11, 12]}
>Solution :
Create dictionary with 3 key and 4 not consecutive values
# Creates a list with values from 1 to 12
overs = list(range(1, 13))
print(overs)
# Creates a dictionary where the values of the list are inserted into the values of the dictionary
players = {"A": [], "B": [], "C": []}
for player in players:
prev_value = None # Store the previous value for each player
while len(players[player]) < 4 and overs: # Stop when the list is empty or the player's list has 4 elements
current_value = overs.pop(0) # Take the first value from the list
if prev_value is not None and abs(current_value - prev_value) == 1: # Check for consecutive values
overs.append(current_value) # Reinsert the consecutive value back to the list
else:
players[player].append(current_value)
prev_value = current_value
print(players)