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

Dictionary object has no attribute split

My data file looks like this:

{'data': 'xyz', 'code': '<:c:605445>  **[Code](https://traindata/35.6547,56475', 'time': '2021-12-30T09:56:53.547', 'value': 'True', 'stats': '96/23', 'dupe_id': 'S<:c-74.18'}

I’m trying to print this line:

35.6547,56475

Here is my code:

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

data = "above mentioned data"
for s in data.values():
    print(s)
while data != "stop":
        if data == "quit":
            os.system("disconnect")
        else:
            x, y = s.split(',', 1)

The output is:

{'data': 'xyz', 'code': '<:c:605445>  **[Code](https://traindata/35.6547,56475', 'time': '2021-12-30T09:56:53.547', 'value': 'True', 'stats': '95/23', 'dupe_id': 'S<:c-74.18'}
x, y = s.split(',', 1)
AttributeError: 'dict' object has no attribute 'split'

I’ve tried converting it into tuple, list but I’m getting the same error. The input in x,y should be the above mentioned expected output (35.6547,56475).
Any help will be highly appreciated.

>Solution :

You can do it like this:

x,y = d['code'].split('/')[-1].split(',')

That means, you need to access the dictionary by one of it’s keys, here you want to go for ‘code’. You retrieve the string ‘<:c:605445> **[Code](https://traindata/35.6547,56475&#8217; which you can now either parse via regex or you just do a split at the ‘/’ and take the last element of it using [-1]. Then you can just split the remaining numbers, that you are actually looking for and write them to x and y respectively.

Of course, you might want to check your incoming data to be valid by catching the KeyError you mentioned in the comments:

try:
  x,y = d['code'].split('/')[-1].split(',')
except KeyError:
  print(f'Data invalid. Key "code" not found. Got: {data} instead')
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