'Python : AttributeError: 'NoneType' object has no attribute 'append'
My program looks like
# global
item_to_bucket_list_map = {}
def fill_item_bucket_map(items, buckets):
global item_to_bucket_list_map
for i in range(1, items + 1):
j = 1
while i * j <= buckets:
if j == 1:
item_to_bucket_list_map[i] = [j]
else:
item_to_bucket_list_map[i] = (item_to_bucket_list_map.get(i)).append(j)
j += 1
print "Item=%s, bucket=%s" % (i, item_to_bucket_list_map.get(i))
if __name__ == "__main__":
buckets = 100
items = 100
fill_item_bucket_map(items, buckets)
When I run this, it throws me
AttributeError: 'NoneType' object has no attribute 'append'
Not sure why this would happen? When I am already creating a list at start of each j
Solution 1:[1]
[...]
for i in range(1, items + 1):
j = 1
while i * j <= buckets:
if j == 1:
mylist = []
else:
mylist = item_to_bucket_list_map.get(i)
mylist.append(j)
item_to_bucket_list_map[i] = mylist
j += 1
print "Item=%s, bucket=%s" % (i, item_to_bucket_list_map.get(i))
The while loop, however, can be simplified to
for j in range(1, buckets / i + 1): # + 1 due to the <=
if j == 1:
mylist = []
else:
mylist = item_to_bucket_list_map.get(i)
mylist.append(j)
item_to_bucket_list_map[i] = mylist
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | glglgl |
