You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python字典转换为列表?练习册任务求解

嘿,刚好在刷Python练习册是吧?我来帮你把这个lexicon字典转成需要的列表,给你两种实用的方法,按需选就行:

方法1:用字典自带的items()快速转换

字典的items()方法会直接返回所有键值对的视图,咱们直接把它转成列表就搞定了:

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'
}

# 转换为包含元组的列表
lexicon_list = list(lexicon.items())
print(lexicon_list)

输出会是这种形式:[('north', 'direction'), ('south', 'direction'), ...],每个键值对是一个元组。

方法2:用列表推导式生成子列表

如果你想要每个元素是列表而不是元组,用列表推导式就能轻松实现:

lexicon_list = [[key, value] for key, value in lexicon.items()]
print(lexicon_list)

这次输出就是[['north', 'direction'], ['south', 'direction'], ...],每个键值对变成了子列表。

小提醒
  • Python 3.7及以上版本的字典默认会保留插入顺序,所以转换后的列表顺序和你字典里写的顺序一致;要是用的是更早的版本,可能需要用collections.OrderedDict来保证顺序,但现在基本不用操心这个啦。
  • 你原来的字典最后那个'c...'没写完,记得补全完整的键值对哦,不然会报语法错误哒!

内容的提问来源于stack exchange,提问作者Moo Ima Fish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:42:12