简体   繁体   中英

Why aren't i able to append the values in my dictionary?

keys = [1,2,3,5,6,7,8,9]
squares_dict = {key: None for key in keys}

def box_number(my_dict,xmax,ymax,xmin,ymin,key):
    ra = Rectangle(float(xmax),
                   float(ymax),
                   float(xmin),
                   float(ymin))
    # print(area(ra, Rectangle(float(my_dict[key][2][0]),float(my_dict[key][3][0]),0,0)))
    if area(ra, Rectangle(float(my_dict[key][2][0]),float(my_dict[key][3][0]),0,0)) == area(ra,ra):

        squares_dict[1].append(key,xmax,ymax,xmin,ymin)//This line

The issue i'm having is related to the last line of the code shared, the error i'm getting is squares_dict[1].append(key,xmax,ymax,xmin,ymin) AttributeError: 'NoneType' object has no attribute 'append'

squares_dict = {key: None for key in keys}表示squares_dict持有键,每个键的值为None ,这反过来意味着squares_dict[1]是 None 并且NoneType没有 append 属性

You have to change None to a proper value. For example instead of None try a variable thats defined or a string/integer

all your values are None in your dict. You could create empty lists as values.

squares_dict = {key: [] for key in keys}

or even better maybe, get rid of the creation and use defaultdict

import collections
squares_dict = collections.defaultdict(list)

so first time, if key isn't in the dict, the defaultdict creates a new, empty list.

And after that, you have to append a tuple , not several values ( append only accepts one argument):

squares_dict[1].append((key,xmax,ymax,xmin,ymin))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM