Home > Net >  how to convert the dictionary string to dictionary int?
how to convert the dictionary string to dictionary int?

Time:04-17

A = {'1': '[1,2]', '2': '[3,4]', '3': '[5,6]', '4': '[7,8]', '5': '[9,10]' }
B = {'1': '70', '2': '70', '3': '70', '4': '70', '5': '70' }

How to convert this multiple string dictionary into int dictionary?

Desired result :-

A = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[4,5], 5:[5,6] }
B =  { 1:70, 2:70, 3:70, 4:70, 5:70 }

CodePudding user response:

You can convert the string [1, 2] to list of int with ast.literal_eval. For example:

from ast import literal_eval

A = {"1": "[1,2]", "2": "[3,4]", "3": "[5,6]", "4": "[7,8]", "5": "[9,10]"}
B = {"1": "70", "2": "70", "3": "70", "4": "70", "5": "70"}


A = dict(tuple(map(literal_eval, i)) for i in A.items())
B = dict(tuple(map(literal_eval, i)) for i in B.items())

print(A)
print(B)

Prints:

{1: [1, 2], 2: [3, 4], 3: [5, 6], 4: [7, 8], 5: [9, 10]}
{1: 70, 2: 70, 3: 70, 4: 70, 5: 70}

CodePudding user response:

Without special library:

import json

A = {"1": "[1,2]", "2": "[3,4]", "3": "[5,6]", "4": "[7,8]", "5": "[9,10]"}
B = {"1": "70", "2": "70", "3": "70", "4": "70", "5": "70"}

A = {int(key): json.loads(val) for key, val in A.items()}
B = {int(key): json.loads(val) for key, val in B.items()}

print(A)
print(B)
  • Related