Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Dictionary Throwing KeyError for adding list of tuples

Here is original text file:

s1 10 s2
s2 12 s3
s3 25 s1
s1 14 s3

I am making a dictionary of first value in each line as a key, the output should be:
{‘s1’: [(‘s2’, ‘s10’), (‘s3′, ’14’)], ‘s2’: [(‘s3′, ’12’)], ‘s3’: [(‘s1′, ’25’)]}

When i run my code I get a key error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def graph_dict(filename):
    dictx = {}
    with open(filename) as x:
        for i in x:
            c, c1, c2 = i.split()
            dictx[c] += [(c2,c1)]
        return dictx

Traceback (most recent call last):
  File "<pyshell#361>", line 1, in <module>
    graph_dict("filename.txt")
  File "*********************************************", line 7, in graph_dict
    dictx[c] += [(c2,c1)]
KeyError: 's1'

in the above line when I make it into dictx[c] = [(c2,c1)] I get output;

{'s1': [('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]}

And so it is throwing a key error as attempting to add a list of 2 tuples to "s1", which I thought should be okay. Does anyone have advice to get output:

{'s1': [('s2', 's10'), ('s3', '14')], 's2': [('s3', '12')], 's3': [('s1', '25')]}

Thanks

>Solution :

dictx[c] += [(c2,c1)] assumes that c already exists in the dictionary. You could test instead. And use .append to be a little faster.

def graph_dict(filename):
    dictx = {}
    with open(filename) as x:
        for i in x:
            c, c1, c2 = i.split()
            if c in dictx:
                dictx[c].append((c2,c1))
            else:
                dictx[c] = [(c2, c1)]
        return dictx
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading