函数返回字符串而不是字典

时间:2020-03-07 04:49:55

标签: python python-3.x string dictionary

我有一个名为“随机单词”的程序包,它每天都会生成一个随机单词。

这是主程序:

from random_word import RandomWords

r = RandomWords()
word = r.word_of_the_day()
print( word )

这是输出:

'{"word": "daedal", "definations": [{"source": "gcide", "text": "Cunningly or ingeniously formed or working; skillful; artistic; ingenious.", "note": null, "partOfSpeech": "adjective"}, {"source": "gcide", "text": "Crafty; deceitful.", "note": null, "partOfSpeech": "adjective"}]}'

我知道这是一个简单的问题,但是除了使用exec()的网页,我可以在网上找到其他任何内容 返回类型是字符串,我不能像字典一样使用它。我该如何解决?我尝试使用exec()eval()或转换为list()dict()甚至set(),但没有任何效果。

这是使用exec()时的代码:

from random_word import RandomWords

r = RandomWords()
word = exec(r.word_of_the_day())

这是错误消息:

Traceback (most recent call last):
  File "c:\Users\filip\Desktop\test_words.py", line 4, in <module>
    word = exec(r.word_of_the_day())
  File "<string>", line 1, in <module>
NameError: name 'null' is not defined

1 个答案:

答案 0 :(得分:4)

您可以使用json.loads https://docs.python.org/3/library/json.html

import json

string_val = '{"word": "daedal", "definations": [{"k":"v"}]}'
dict_val = json.loads(string_val)

print(dict_val['word'])

输出

daedal