Python: Unable to convert integer to string JSON's value

91 Views Asked by At

In python, trying to convert the key-value pair from integer to string.

Input:

data = [
    {'code': 123456, 'value': 32},
    {'code': 987654, 'value': 12}
]

Expected Output

data = [
    {'code': '123456', 'value': 32},
    {'code': '987654', 'value': 12}
]

Trying for code-value.

2

There are 2 best solutions below

0
On

Here's a dictionary comprehension inside a list comprehension to achieve this:

data = [
    {'code': 123456, 'value': 32},
    {'code': 987654, 'value': 12}
]

new_data = [{k: str(v) if k == 'code' else v for k, v in d.items()} for d in data]

where new_data will hold the data in your desired format as:

[{'code': '123456', 'value': 32}, {'code': '987654', 'value': 12}]

Inside the dictionary comprehension I am checking whether the key is 'code', and type-casting the value to str in case of a match.

0
On
for row in data:
    row['code'] = str(row['code'])