在python中输入“string”到“dict”

时间:2017-09-28 15:47:15

标签: python

我是python中的新手。我正在阅读源代码并得到一些疑问。

def parse_json_in_str(data):
# parse json and convert everything from unicode to str
return json.loads(data, object_hook=_decode_dict)

变量“config”在这里是一个字符串(parse_json_in_str)。这里是parse_json_in_str:

 v_count = 0
    for key, value in optlist:
        if key == '-p':
            config['server_port'] = int(value)
        elif key == '-k':
            config['password'] = to_bytes(value)
        elif key == '-l':
            config['local_port'] = int(value)
        elif key == '-s':
            config['server'] = to_str(value)
        elif key == '-m':
            config['method'] = to_str(value)
        elif key == '-b':
            config['local_address'] = to_str(value)
        elif key == '-v':
            v_count += 1
            # '-vv' turns on more verbose mode
            config['verbose'] = v_count
        elif key == '-t':
            config['timeout'] = int(value)

        .....
        elif key == '-q':
            v_count -= 1
            config['verbose'] = v_count
except getopt.GetoptError as e:
    print(e, file=sys.stderr)
    print_help(is_local)
    sys.exit(2)

然后:

var keymap = collection.mutable.Map[Int,String]()
val content = Source.fromFile("abc.csv").getLines;
val data = content.drop(1); //to remove header
for (line <-data){   
    val x = line.substring(0,1).toInt;
    val y = line.substring(2,4).toInt;
    var key = (x*100) + y;
    var value = line.substring(9);
    var keymap += (key,value);
}

为什么“配置”会变成字典?

1 个答案:

答案 0 :(得分:0)

在这种情况下,json.loads返回一个字典...... the json docs说,

  

使用此转换表将s(包含JSON文档的str或unicode实例)反序列化为Python对象。

conversion table表示json对象转换为id