Python Forum
Converting '1a2b3c' string to Dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting '1a2b3c' string to Dictionary
#1
Hello, I'm currently in school for computer science, graduating next year and I've been browsing some of the leetcode problems. I was a bit disheartened as when I read some of the answers it looks like I'm reading a foreign language. I've been trying to give myself simple problems so I can get comfortable converting different types of data to dictionaries, I still have a few classes to take but have not really worked with them. What I've been trying to do is convert the string '1a2a3c' into a dictionary {1 : a, 2 : b, 3 : c} using a for a loop. Eventually, I want to create a function that does this. So far I've only been able to come up with this

s = '1a2b3c' 
keys = []
keys[:0] = s
dic = {}
for i in keys:
    if (keys.index(i) % 2) == 0:
        dic[keys[i]] = keys[i + 1]
But when I try to run this I get the error

Error:
Traceback (most recent call last): File "<string>", line 7, in <module> TypeError: can only concatenate str (not "int") to str
Does anyone know what I'm doing wrong?
Larz60+ write May-12-2022, 06:09 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use BBCode tags on future posts.
Reply


Messages In This Thread
Converting '1a2b3c' string to Dictionary - by PythonNoobLvl1 - May-12-2022, 05:39 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help converting string to int dedesssse 7 2,676 Jul-07-2021, 09:32 PM
Last Post: deanhystad
  Beautify dictionary without converting to string. sharoon 6 3,373 Apr-11-2021, 08:32 AM
Last Post: buran
  how to deal with problem of converting string to int usthbstar 1 1,967 Jan-05-2021, 01:33 PM
Last Post: perfringo
  Converting data in CSV and TXT to dictionary kam_uk 3 1,983 Dec-22-2020, 08:43 PM
Last Post: bowlofred
  Converting string to hex triplet menator01 4 4,315 Aug-03-2020, 01:00 PM
Last Post: deanhystad
  extract a dictionary from a string berc 4 2,851 Jul-30-2020, 06:58 AM
Last Post: berc
  simple f-string expressions to access a dictionary Skaperen 0 1,522 Jul-15-2020, 05:04 AM
Last Post: Skaperen
  converting string object inside a list into an intiger bwdu 4 2,603 Mar-31-2020, 10:36 AM
Last Post: buran
  problem coverting string data file to dictionary AKNL 22 6,423 Mar-10-2020, 01:27 PM
Last Post: AKNL
  Converting query string as a condition for filter data. shah_entrance 1 1,785 Jan-14-2020, 09:22 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020