我有一本字典:
watch_list= {'videos': [{'systemId': 'qre', 'duration': 19}, {'systemId': 'abc', 'duration': 19}]}
现在,我想检查字典中是否已经存在该持续时间,如果存在,则通过systemId更新systemId。
因此,我尝试使用以下代码:
def update_duration(watch_list,system_id,duration):
watch_history= next((a for a in watch_list if a['systemId'] == system_id), None)
if watch_history:
watch_history['duration'] =duration
return watch_history
但这给了我一个错误:
*** TypeError: string indices must be integers
我是python的新手,我读过堆栈溢出的其他解决方案,但不能让它工作。有没有人能帮我一点忙,告诉我如何通过systemId更新值?
我用的是python 3和flask
发布于 2019-05-24 03:32:05
当您使用如下内容遍历字典时
my_dictionary = { 'hello' : ['I', 'am', 'a', 'dictionary'] }
for entry in my_dictionary:
print entry
默认情况下,输出将是hello
,因为它会遍历它的键。看起来您实际上希望遍历字典的值,因此您需要调用values()
函数,或者调用Python2中的itervalues()
。
除此之外,您还会遇到生成器理解的if语句的问题。在这一点上,您的a
变量保存了一个字典列表-曾经是watch_list['videos']
找到的值。
https://stackoverflow.com/questions/56280683
复制相似问题