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

split string value in a python dict

I have a dict with a key value pair where some have one position ex. ‘A’ and some have multiple positions ex. ‘A,B’ . Is there a way for me to split the ones with multiple positions so I can use both. I’m currently getting a key error because python wants to look up ‘A,B’ when I want it to look up ‘A’,’B’. Please see below.

dict = {1 : 'A' , 2: 'A,B' , 3:'C,D'}

if I wanted to print to values for 2 I would want the out put to be:

A
B

or some form where they are separate so I will stop getting the 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

Here is the actual bit of code with the KeyError for my project that is causing me trouble.

         for pos in playerPos[player]:
             team_pos[playerPos[player]] += 1
             

KeyError: '1B,OF'

>Solution :

You need to iterate over the split value:

for pos in playerPos[player].split(','):
    team_pos[pos] += 1
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