'how to convert the dictionary string to dictionary int?
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 }
Solution 1:[1]
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}
Solution 2:[2]
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)
Solution 3:[3]
Here is another solution:
A = {'1': '[1,2]', '2': '[3,4]', '3': '[5,6]', '4': '[7,8]', '5': '[9,10]' }
new_dict = {}
for key, value in A.items():
new_dict[int(key)] = eval(value)
print(new_dict)
Output:
{1: [1, 2], 2: [3, 4], 3: [5, 6], 4: [7, 8], 5: [9, 10]}
Do the same thing for dictionary B.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andrej Kesely |
Solution 2 | Nechoj |
Solution 3 | Jake Korman |