【问题标题】:Function returns string instead of dictionary [duplicate]函数返回字符串而不是字典[重复]
【发布时间】:2020-03-07 04:49:55
【问题描述】:

我有一个名为“random-words”的包,它每天都会生成一个随机词。

这是主程序:

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

【问题讨论】:

    标签: python python-3.x string dictionary


    【解决方案1】:

    你可以使用 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
    

    【讨论】:

    • 感谢您的回答:)。想到了json但是不知道怎么正确使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 2013-05-16
    相关资源
    最近更新 更多