JianYA
JianYA

Reputation: 3024

Python dictionary key value swapped?

I'm learning how to use a dictionary in python. However, it seems like when I print my dictionary, some items in my dictionary are swapped. Eg. [key,value],[value,key],[value,key],[key,value].

Is there something I'm missing?

def create_neighbourhood():
    maingrid = []
    coord_grid = {}
    grid = ['A','B','C','D','E','F','G','H','I','J']
    for i in range(0,len(grid)):
        for j in range(0,10):
            current_cell = grid[i]+ str(j+1)
            current_coords = str(i) +","+str(j)
            coord_grid = {current_cell,current_coords}
            maingrid.append(coord_grid)
    return maingrid

Upvotes: 0

Views: 103

Answers (1)

Neil
Neil

Reputation: 14313

Why

You are using sets instead of dictionaries. You must divide the two items by a : not a , . Sets don't enforce order so the elements will be periodically swapped with this implementation.

New Code

def create_neighbourhood():
    maingrid = []
    coord_grid = {}
    grid = ['A','B','C','D','E','F','G','H','I','J']
    for i in range(0,len(grid)):
        for j in range(0,10):
            current_cell = grid[i]+ str(j+1)
            current_coords = str(i) +","+str(j)
            coord_grid = {current_cell:current_coords}
            maingrid.append(coord_grid)
    return maingrid

print(create_neighbourhood())

Upvotes: 3

Related Questions