Home > Mobile >  how to convert dictionary values ​from str to int (list values)?
how to convert dictionary values ​from str to int (list values)?

Time:02-19

I need to convert dictionary values ​​from str to int (list values)

I have this

d = {'12345': ['paper', '3'], '67890': ['pen', '78'], '11223': ['olive', '100'], '33344': ['book', '18']}

But i need this one

{'12345': ['paper', 3], '67890': ['pen', 78], '11223': ['olive', 100], '33344': ['book', 18]}

i tried this:

for i,v in d.items():
    d[i] = int(v[1])
print(d)

i got this:

{'12345': 3, '67890': 78, '11223': 100, '33344': 18}

But i need this one:

{'12345': ['paper', 3], '67890': ['pen', 78], '11223': ['olive', 100], '33344': ['book', 18]}

I have no idea how to do this. Maybe someone knows how to do it?

CodePudding user response:

You were close, but it's simpler to just go over the values instead of the items.

for v in d.values():
    v[1] = int(v[1])

CodePudding user response:

d[key]=value -> to insert {key:value} into dictionary
d[i] = int(v[1]) This will only insert v[1]'s interger value but we want list of values to insert, so we need to use [v[0],int(v[1])]

for i,v in d.items():
    d[i] =[v[0],int(v[1])]
print(d)
  • Related