I'm working with an api that returns json formatted as a list (of a list) of dictionaries similar to this:
list_of_dictionaries = [
[{'key1':0},{'key2':1}],
[{'key1':2},{'key2':3}],
[{'key1':4},{'key2':5}],
[{'key1':6},{'key2':7}],
[{'key1':8},{'key2':9}]
]
I also have a separate list of tuples that contain coordinates:
coordinates_tuple = namedtuple('Coordinates', ['x','y'])
coordinates_list = []
coordinates_list.append(coordinates_tuple((0),(0)))
coordinates_list.append(coordinates_tuple((1),(0)))
coordinates_list.append(coordinates_tuple((1),(1)))
coordinates_list.append(coordinates_tuple((0),(1)))
coordinates_list.append(coordinates_tuple((-1),(-1)))
My goal is to add each coordinates_tuple as a key/value pair within list_of_dictionaries so I created this for loop which seems to achieve the desired output:
for i in range(len(list_of_dictionaries)):
x = coordinates_list[i].x
y = coordinates_list[i].y
coordinates_dictionary = {'x' : x , 'y' : y}
list_of_dictionaries[i].append(coordinates_dictionary.copy())
print(list_of_dictionaries[i])
#output
#[{'key1': 0}, {'key2': 1}, {'x': 0, 'y': 0}]
#[{'key1': 2}, {'key2': 3}, {'x': 1, 'y': 0}]
#[{'key1': 4}, {'key2': 5}, {'x': 1, 'y': 1}]
#[{'key1': 6}, {'key2': 7}, {'x': 0, 'y': 1}]
#[{'key1': 8}, {'key2': 9}, {'x': -1, 'y': -1}]
Assuming these two lists will always be the same length and sequentially ordered (coordinates_list[0] will match with list_of_dictionaries[0]) - does this approach make sense or is there a better solution?