1

Below is my code.

test_str = '1:20,3:4,5:30'
res = []
for sub in test_str.split(','):
    if ':' in sub:
        res.append(map(str.strip, sub.split(':', 1)))
res = dict(res)
print(res) // result {'1': '20', '3': '4', '5': '30'}

This gives me dict but with type str but I want to be type of int. How should I convert it?

Any leads, please?

Viswanatha Swamy
  • 699
  • 1
  • 10
  • 17
user1298426
  • 3,467
  • 15
  • 50
  • 96
  • `This gives me dict but with type str` >> This doesn't make sense. dict is of type dict. I assume you mean that you either want the key to be int, or the value to be of type int? – Devesh Kumar Singh Jul 05 '21 at 03:08
  • `res.append(map(lambda x: int(str.strip(x)), sub.split(':', 1)))` ? – Epsi95 Jul 05 '21 at 03:11
  • ```res.append([int(i.strip()) for i in sub.split(':', 1)])```? –  Jul 05 '21 at 03:17

2 Answers2

2

You can just use eval or ast.literal_eval appending opening and closing curly braces at the beginning and the end of your string representation.

>>> import ast
>>> ast.literal_eval('{'+test_str+'}')
{1: 20, 3: 4, 5: 30}
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • 1
    please use `ast.literal_eval('{1:20,3:4,5:30}')` – Epsi95 Jul 05 '21 at 03:10
  • [Why is using 'eval' a bad practice?](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Selcuk Jul 05 '21 at 03:16
  • @Epsi95, I modified the code to use `ast_eval`, but both are identical; however, I also think using `ast.litera_eval` makes more sense since it evaluates the literal, not the actual code. – ThePyGuy Jul 05 '21 at 03:17
  • That's much simpler than I thought :-) – user1298426 Jul 05 '21 at 03:17
  • Also consider using f-strings instead of string concatenation, i.e. `ast.literal_eval(f'{{{test_str}}}')` – Selcuk Jul 05 '21 at 03:19
  • @Selcuk, I was thinking to use that, but it will unnecessarily create confusion due to the need of using double braces to be used as escape character. – ThePyGuy Jul 05 '21 at 03:22
  • 1
    @ThePyGuy One minor disadvantage is that this won't validate that its a key-pair (as in the original loop) ... eg it will happily return a **set** for the input `"1,2,3"` (in Python3, in Python2 it will die on that input) – donkopotamus Jul 05 '21 at 03:23
  • `dict(map(lambda x: x.split(":"), test_str.split(",")))`, not as elegant as `ast.literal_eval` but get the job done. – mikey Jul 05 '21 at 04:14
0
s="1:20,3:4,5:30"
d ={}
l =s.split(",")
l1=[]
for i in l:
   l2 = i.split(":")
   l1.append(l2)
   l2 = []

for j in l1:
   d[j[0]] =j[1]

What this code does is that it first converts string into a dictionary spliting it by"," and then t takes each element of the list and converts it into the dictionary taking 1st element as key and last element as its value