all_list = [['G05', 'Hopscotch', 'N', '2'], ['G07', 'Dominoes', 'S', '5'], ['G08', 'Chess', 'N', '3'], ['G10', 'Monopoly', 'N', '3'], ['G02', 'MineCraft', 'S', '5']]
game_match = {'G02': [5, 3, 2, 0, 0], 'G05': [5, 3, 2, 0, 0], 'G07': [5, 2, 3, 0, 2], 'G08': [5, 2, 3, 1, 2], 'G10': [5, 1, 4, 2, 2]}
- GXX = game_id
- for the same game id between all_list and game_match, I want to move the game name (index[1] in all_list data) to the index[0] in game_match values, but it moved to index[-1] instead.
for k, v in game_match.items():
for data in all_list:
if k == data[0]:
game_match[k].append(data[1])
print(game_match)
Output:
{'G02': [5, 3, 2, 0, 0, 'MineCraft'], 'G05': [5, 3, 2, 0, 0, 'Hopscotch'], 'G07': [5, 2, 3, 0, 2, 'Dominoes'], 'G08': [5, 2, 3, 1, 2, 'Chess'], 'G10': [5, 1, 4, 2, 2, 'Monopoly']}
Expected output:
{'G02': ['MineCraft',5, 3, 2, 0, 0], 'G05': ['Hopscotch', 5, 3, 2, 0, 0], 'G07': ['Dominoes', 5, 2, 3, 0, 2], 'G08': [ 'Chess', 5, 2, 3, 1, 2,\], 'G10': ['Monopoly', 5, 1, 4, 2, 2]}
CodePudding user response:
Python list have a special method for inserting element to specific indexes - List.insert(index)
.
In your case the solution would be:
game_match[k].insert(0, data[1])
CodePudding user response:
To insert an element to first position of a list, you can use list_name.insert(index, value)
.
Try this :
all_list = [['G05', 'Hopscotch', 'N', '2'], ['G07', 'Dominoes', 'S', '5'], ['G08', 'Chess', 'N', '3'], ['G10', 'Monopoly', 'N', '3'], ['G02', 'MineCraft', 'S', '5']]
game_match = {'G02': [5, 3, 2, 0, 0], 'G05': [5, 3, 2, 0, 0], 'G07': [5, 2, 3, 0, 2], 'G08': [5, 2, 3, 1, 2], 'G10': [5, 1, 4, 2, 2]}
for k, v in game_match.items():
for data in all_list:
if k == data[0]:
game_match[k].insert(0, data[1])
print(game_match)
Output:
{'G05': ['Hopscotch', 5, 3, 2, 0, 0], 'G07': ['Dominoes', 5, 2, 3, 0, 2], 'G08': ['Chess', 5, 2, 3, 1, 2], 'G02': ['MineCraft', 5, 3, 2, 0, 0], 'G10': ['Monopoly', 5, 1, 4, 2, 2]}