Try changing the last line to this in order to avoid key errors:
sum(item['key'] for item in array if 'key' in item)
Question
The following code:
for j in reversed(range(0,15)):
print i
successors = g.successors(totuple(total_nodes[j,:]))
array = [0,0,0,0]
a=0
i = i+1
for succ in successors:
print g.node[succ]
array[a]=g.node[succ]
a+=1
print array
print sum(item['key'] for item in array)
produces the following output:
1
{'key': 0.0}
{'key': 0.39730768970355257}
{}
{'key': 0.0}
[{'key': 0.0}, {'key': 0.39730768970355257}, {}, {'key': 0.0}]
So based on other questions I tried:
print sum(item['key'] for item in array)
produces:
KeyError: 'key'
print sum([i for i in array.values()])
produces:
AttributeError: 'list' object has no attribute 'values'
La solution
Try changing the last line to this in order to avoid key errors:
sum(item['key'] for item in array if 'key' in item)
Autres conseils
you can use sum(item.get('key', 0)) for item in array)
which would return 0
if key
is not found
Some of your nodes are lists or integers -- which is why, not being dicts, they don't have a values()
method and can't be indexed with string keys.
As for why your data is structured so, we can't tell you unless you give us more context (like, what's g
? What does successors()
do? totuple()
? What is the actual problem you're attempting to solve?).