Python 如何将值字典转换为列表
我正在处理python工作簿,我必须将以下词典转换为列表:Python 如何将值字典转换为列表,python,list,dictionary,Python,List,Dictionary,我正在处理python工作簿,我必须将以下词典转换为列表: lexicon = { 'north': 'direction', 'south': 'direction', 'east': 'direction', 'west': 'direction', 'down': 'direction', 'up': 'direction', 'left': 'direction', 'right': 'direction', 'ba
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'}
但我在互联网上找不到任何有助于我这么做的东西。我怎样才能把它变成一个列表呢?谢谢你的帮助 您可以使用.keys()
或.values()
您可以使用.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')]
如果您只需要值,可以使用:
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')]
希望这有帮助你可以试试
列表(词典)
。如果这不符合你想要的,考虑解释你想要什么。你想要什么样的输出列表?词汇=[‘北’、‘南’、‘东’]?或者lexicon=['north','direction','south','direction','east''direction']?看看lexicon.items()你的问题不清楚。是否要将所有名词和所有动词组合在一起?可能值得注意的是列表(词典)
也将返回键列表。
>>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')]