[英]Python: Unable to convert integer to string JSON's value
In python, trying to convert the key-value pair from integer to string.在 python 中,尝试将键值对从 integer 转换为字符串。
Input:输入:
data = [
{'code': 123456, 'value': 32},
{'code': 987654, 'value': 12}
]
Expected Output预计 Output
data = [
{'code': '123456', 'value': 32},
{'code': '987654', 'value': 12}
]
Trying for code-value.尝试代码值。
for row in data:
row['code'] = str(row['code'])
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:其中
new_data
将以您想要的格式保存数据:
[{'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.在字典理解中,我正在检查键是否为
'code'
,并在匹配的情况下将值类型转换为str
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.