1

why am i getting a key error when trying to iterate through a list of key value pairs and count how many times the key occurs? the error i'm getting is something like KeyError: 3, which means the key doesn't exist. can i not add it like this? self.node_degree[source] += 1

class PageRank:
    def __init__(self, edge_file):

        self.node_degree = {}
        self.max_node_id = 0
        self.edge_file = edge_file

    def read_edge_file(self, edge_file):
        with open(edge_file) as f:
            for line in f:
                if line[0] != '%':
                    val = line.split()
                    yield int(val[0]), int(val[1])

    def get_max_node_id(self):
        return self.max_node_id

    def calculate_node_degree(self):

        for source,target in self.read_edge_file(self.edge_file):   
            self.node_degree[source] += 1

zelda26
  • 489
  • 2
  • 10
  • 33

2 Answers2

3

try this

for source,target in self.read_edge_file(self.edge_file):   
    try:
        self.node_degree[source] += 1
    except: 
        self.node_degree[source] = 1

You tried to add 1 to None coz you didn't create the key in dict if there is no such key in dict so in except creating new key of dict will do the work.

Tserenjamts
  • 579
  • 6
  • 15
0

Try

self.node_degree[source] = self.node_degree.get(source, 0) + 1
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
  • Not sure why this got downvoted, I'd say using the `get` method is the canonical way to approach this. – wwii Nov 06 '19 at 17:22