使用字符串创建字典值条目

时间:2015-10-20 22:51:36

标签: python python-2.7 dictionary

假设有一个包含多行词典的文件,

{"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"}

任何人都知道如何获取输入字符串并使其作为父字典的字典值很好地播放?

2 个答案:

答案 0 :(得分:3)

您可以尝试使用split和strip,但最简单的方法是将字符串括在括号中并调用document

ast.literal_eval

输出:

from ast import literal_eval

inp = '"apple": "red", "oarange": "orange", "pear": "green"'


d = literal_eval("{{{}}}".format(inp))

你几乎有一个{'pear': 'green', 'oarange': 'orange', 'apple': 'red'} 的词典,我们唯一缺少的是括号,因此使用带有str.format的'"apple": "red", "oarange": "orange", "pear": "green"'将字符串包装在括号中,允许我们调用"{{{}}}"

另一方面,如果您在文件中有dicts并且实际上是字符串来自哪里,那么您应该直接literal_evaljson.loads每行。

答案 1 :(得分:2)

您可以使用split('"')为您提供战略位置词典的键和值。使用它,可能的解决方案是:

input = '{"apple": "red", "oarange": "orange", "pear": "green"}' # Your input
words = input.split('"')
fruits = words[1::4]  # Location of keys
colors = words[3::4]  # Location of values

d = dict(zip(fruits, colors)) # Create the dictionary
d = {'plate1': d} # Make that dictionary a value of the key 'plate1'
然后

d

{'plate1': {'pear': 'green', 'oarange': 'orange', 'apple': 'red'}}