1

I would like to add an extra key called "centroid" to this loc1 and loc2 dictionary by using some custom centroid calculation function. location_list is the list of dictionaries loc1 and loc2

location_list = [loc1,loc2]

loc1 = {
"x_cor" : 10,
"y_cor" : 20}

loc2 = {
"x_cor" : 10,
"y_cor" : 25}

I would like to get the centroid of these two locations and add an extra key "centroid" to both loc1 and loc2.

The function for calculating centroid is as follows:

 def get_centroid(self, locations: list):
        
        x, y = [p[0] for p in locations], [p[1] for p in locations]
        centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
        return centroid

Expected output:

loc1 = {
    "x_cor" : 10,
    "y_cor" : 20,
"centroid": (6.667 , 15)}
    
    loc2 = {
    "x_cor" : 10,
    "y_cor" : 25,
"centroid": (6.667 , 15)} 

Is there a way I can use this function to add an extra key "centroid" to these dictionaries?

Sam
  • 352
  • 2
  • 4
  • 22

2 Answers2

0
 def get_centroid(self, locations: list):
        
        x, y = [p[0] for p in locations], [p[1] for p in locations]
        centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
        for location in locations:
            location['centroid'] = centroid
        return centroid
Cor
  • 104
  • 2
0

Your get_centroid function does not work. You can't access dictionary items using index as dictionaries are unordered, Index into dictionary.

This means you'll have to replace p[0] for p['x_cor'] and p[1] for p['y_cor'].

I don't think you need self as an argument in get_centroid. self isn't used in the function code and they are used in classes mostly.

To add the centroid to loc1 and loc2 you can use a for loop.

for loc in locations:
        loc['centroid'] = centroid
    return locations

Combine this into your get_centroid function to get this:

def get_centroid(locations: list):
    x, y = [p['x_cor'] for p in locations], [p['y_cor'] for p in locations]
    centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
    for loc in locations:
        loc['centroid'] = centroid
    return locations

Using your supplied x and y co-ordinate values and the centroid equation, I wasn't able to achieve your expected output. The output I achieved for the centroid was (10.0, 22.5).

Whole code

def get_centroid(locations: list):
    x, y = [p['x_cor'] for p in locations], [p['y_cor'] for p in locations]
    centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
    for loc in locations:
        loc['centroid'] = centroid
    return locations

loc1 = {
"x_cor" : 10,
"y_cor" : 20}

loc2 = {
"x_cor" : 10,
"y_cor" : 25}

location_list = [loc1,loc2]

print(get_centroid(location_list))

Output

[{'x_cor': 10, 'y_cor': 20, 'centroid': [10.0, 22.5]}, {'x_cor': 10, 'y_cor': 25, 'centroid': [10.0, 22.5]}]
newToCoding
  • 174
  • 1
  • 1
  • 8