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
#2
Here is one way
string = '1a2b3c4d'
l1 = []
l2 = []
for char in string:
    l1.append(char) if char.isnumeric() else l2.append(char)
mydict = dict(zip(l1,l2))
print(mydict)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
Your problem is you are trying to use a str as a number. You cannot "a" % 2. You can't even "1" % 2. If you want to index the list you need to loop through index values, not list items. You can write your code like this:
keys = list('1a2b3c')
dic = {}
for i in range(len(keys)):
    if (i % 2) == 0:
        dic[keys[i]] = keys[i + 1]
print(dic)
Or better yet:
keys = list('1a2b3c')
dic = {}
for i in range(0, len(keys), 2):
    dic[keys[i]] = keys[i + 1]
print(dic)
Or even better:
keys = list('1a2b3c')
dic = {keys[i]:keys[i+1] for i in range(0, len(keys), 2)}
print(dic)
I would use zip and slices to make (key, value) tuples. The dict() function can use these to make a dictionary
s = "1a2b3c"
sdict = dict(zip(s[::2], s[1::2]))
print(sdict)
s[::2] gets every second character starting at zero ('1', '2', '3').
s[1::2] gets every second character starting at one ('a', 'b', 'c')
zip(s[::2], s[1::2]) generates tuples ('1', 'a'), ('2', 'b'), ('3', 'c')
The dict() function converts the sequence of key, value tuples into a dictionary.
PythonNoobLvl1 and menator01 like this post
Reply
#4
mystring = '1a2b3c4d'
mydict = {mystring[i-1]:mystring[i] for i in range(1, len(mystring), 2)}
menator01 likes this post
Reply
#5
from more_itertools import chunked, sliced

spam = '1a2b3c4d'

# without using more_itertools 
print(dict(zip(spam[::2], spam[1::2])))

# using more_itertools
print(dict(chunked(spam, 2)))
print(dict(sliced(spam, 2, strict=True)))
Output:
{'1': 'a', '2': 'b', '3': 'c', '4': 'd'} {'1': 'a', '2': 'b', '3': 'c', '4': 'd'} {'1': 'a', '2': 'b', '3': 'c', '4': 'd'}
menator01 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Another way could be using built-in zip for clustering a data serie into specified length groups (in this case two) and feed it to built in dict constructor.

From documentation:

Quote:Tips and tricks:

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n, strict=True). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.


>>> s = '1a2b3c4d'
>>> n = 2
>>> dict(zip(*[iter(s)]*n, strict=True))
{'1': 'a', '2': 'b', '3': 'c', '4': 'd'}
deanhystad likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
Using the same iterator to extract both items for each tuple is brilliant. It is not immediately obvious though. It took a minute for me to understand how it worked,
def todict(kvstring):
    i = iter(kvstring)
    return dict(zip(i, i))
Reply


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