说有使用词典的多行文件的字典值项,使用绳子
{"apple": "red", "oarange": "orange", "pear": "green"}
从这个字符串被抓获,对
>>> input = '"apple": "red", "oarange": "orange", "pear": "green"'
>>> input
'"apple": "red", "oarange": "orange", "pear": "green"'
,当然,我可以很容易地捕获它作为
>>> input = '{"apple": "red", "oarange": "orange", "pear": "green"}'
>>> input
'{"apple": "red", "oarange": "orange", "pear": "green"}'
无论如何,我希望采取输入,并使其成为一个新的字典的新价值,所以,使用两种不同的方法,不工作,
>>> mydict['plate1'] = input
>>> mydict['plate2'] = {input}
产生不良
>>> mydict
{'test': set(['"user_name": "BO01", "password": "password", "attend_password": "BO001"']), 'plate1': '"apple": "red", "oarange": "orange", "pear": "green"'}
既不希望的,其中
'plate1' : {"apple": "red", "oarange": "orange", "pear": "green"}
人知道如何取输入字符串,使其作为父字典的字典值可以很好地发挥作用吗?
Tapadh真皮休闲。现在,我刚刚走了,看着'literal_eval'的pydoc,我不明白''{{{}}}''的作用。你能否在答案中解释一下? –
我会接受你的建议并直接从文件中加载,但当然每行中还有其他垃圾需要分解。 –
我加了一点解释,当你在字符串本身中使用'{}'时,它们必须被转义,所以你需要使用'“{{{}}}”',内在就是你通过格式化外部括号只是逃避另一个。如果你在文件中有垃圾,只想要有效的行是dicts,你可以用try/expect来捕捉坏行 –