我正在使用python工作簿,我必须将以下字典转换为列表:
lexicon = {
'north': 'direction',
'south': 'direction',
'east': 'direction',
'west': 'direction',
'down': 'direction',
'up': 'direction',
'left': 'direction',
'right': 'direction',
'back': 'direction',
'go': 'verb',
'stop': 'verb',
'kill': 'verb',
'eat': 'verb',
'the': 'stop',
'in': 'stop',
'of': 'stop',
'from': 'stop',
'at': 'stop',
'it': 'stop',
'door': 'noun',
'bear': 'noun',
'princess': 'noun',
'cabinet': 'noun'}
但我在互联网上找不到任何帮助我这样做的东西。我该如何将其变成列表?感谢帮助!
答案 0 :(得分:1)
您可以使用.keys()
或.values()
。
>>> list(lexicon.keys())
['princess', 'down', 'east', 'north', 'cabinet', 'at', 'right', 'door', 'left', 'up', 'from', 'bear', 'of', 'the', 'south', 'in', 'kill', 'eat', 'back', 'west', 'it', 'go', 'stop']
>>> list(lexicon.values())
['noun', 'direction', 'direction', 'direction', 'noun', 'stop', 'direction', 'noun', 'direction', 'direction', 'stop', 'noun', 'stop', 'stop', 'direction', 'stop', 'verb', 'verb', 'direction', 'direction', 'stop', 'verb', 'verb']
您可以使用.items()
将键值对作为元组列表
>>> list(lexicon.items())
[('princess', 'noun'), ('down', 'direction'), ('east', 'direction'), ('north', 'direction'), ('cabinet', 'noun'), ('at', 'stop'), ('right', 'direction'), ('door', 'noun'), ('left', 'direction'), ('up', 'direction'), ('from', 'stop'), ('bear', 'noun'), ('of', 'stop'), ('the', 'stop'), ('south', 'direction'), ('in', 'stop'), ('kill', 'verb'), ('eat', 'verb'), ('back', 'direction'), ('west', 'direction'), ('it', 'stop'), ('go', 'verb'), ('stop', 'verb')]
答案 1 :(得分:0)
如果您只想要可以使用的值:
lexicon.values()
它将返回针对每个密钥保存的值。
但是如果您想要一个键值对列表,那么您可以使用以下内容:
>>lexicon.items()
output :
[('right', 'direction'), ('it', 'stop'), ('down', 'direction'), ('kill', 'verb'), ('at', 'stop'), ('in', 'stop'), ('go', 'verb'), ('door', 'noun'), ('from', 'stop'), ('west', 'direction'), ('eat', 'verb'), ('east', 'direction'), ('north', 'direction'), ('stop', 'verb'), ('bear', 'noun'), ('back', 'direction'), ('cabinet', 'noun'), ('princess', 'noun'), ('of', 'stop'), ('up', 'direction'), ('the', 'stop'), ('south', 'direction'), ('left', 'direction')]
希望这会有所帮助