【发布时间】:2020-07-30 01:08:49
【问题描述】:
考虑到一个词,我想在字典中搜索它,首先作为键,然后作为值。
我是这样实现的:
substitution_dict={'land':['build','construct','land'],
'develop':['develop', 'builder','land']}
word='land'
key = ''.join([next(key for key, value in substitution_dict.items() if word == key or word in value)])
这个想法是利用短路,单词首先与键进行比较,否则与值进行比较。但是,我想在找到密钥时停止。
运行上面的 sn-p 效果很好。但是,当word 更改为字典中不存在的其他单词时,由于下一条未找到结果的语句,它会抛出StopIteration 错误。
我想知道这是否可以按照我的意图在一行中实现。
谢谢
【问题讨论】:
-
为什么要使用
''.join()?您的列表中只有一个元素。 -
我想从字典中的键或值中获取字符串。
-
如果字典中没有这个词,究竟应该发生什么?为什么不正常捕获异常?
标签: python dictionary list-comprehension next