我有一个“天气:getWeather”形式的字符串,我需要将其转换为下面的字典
{
"RemoteService": "Weather",
"RemoteApi": "getWeather",
}
目前这就是我正在做的事情
remote_service, remote_api = remote_signature.split(":")
service_metrics["RemoteService"] = remote_service
service_metrics["RemoteApi"] = remote_api
虽然这可能没关系,但是好奇的是,有没有更好的pythonic方式呢?
答案 0 :(得分:5)
dict
将接受键值元组列表以生成新词典。
keys = ['RemoteService', 'RemoteApi']
values = 'Weather:getWeather'.split(':')
service_metrics = dict(zip(keys, values))
答案 1 :(得分:2)
字典理解:
{ k:v for k,v in zip ( ['RemoteService', 'RemoteApi' ],
"Weather:getWeather".split( ':' ) ) }
答案 2 :(得分:1)
使用json库:
import json
remote_signature = """{"RemoteService":"Weather","RemoteApi":"getWeather"}"""
remote_dict = json.loads(remote_signature)