Search code examples
pythondictionarynestedtuplescartesian-coordinates

Python is it possible to store tuple coordinates in a nested dict and access a single coordinate from a single dict within the nested dict?


I have some code that uses a dict to store coordinate values. I would prefer to have something that had a key 'R1N1' and the value would be a tuple of the x and y coordinates but I don't know if that is possible in python or how you would index a key-tuple for either its x or y component:

Code

import json

rnID = dict ([
('R1N1x', 1),
('R1N1y', 111),
('R1N500x', 222),
('R1N500y', 222),
('R2N1x', 1),
('R2N1y', 111),
('R2N500x', 222),
('R2N500y', 222)
])

with open('rnID.txt', 'w') as outfile:
    json.dump(rnID, outfile)

this works at storing coordinates but is a bit longwinded.

Desired output

something like 
new_dict = {[
('R1N1',(1,111))
...

Solution

  • Here you go:

    rns = {}
    for k, v in rnID.items():   
        part = k[-1]
        k = k[:-1]
        if k not in rns:
            rns[k] = [0, 0]
        rns[k][0 if part == 'x' else 1] = v
    
    print(rns)
    

    Output

    {'R1N1': [1, 111], 'R1N500': [222, 222], 'R2N1': [1, 111], 'R2N500': [222, 222]}