如何通过密钥访问列表?

How to Access a List through a key?

我有一个程序,它有一个充满列表的保存文件。它通过列出列表来加载项目。它也从文件中获取名称。因为我不能 "unstring" 一个字符串,所以我把名字作为键。我的问题是在您使用完该程序后重新保存列表。我似乎无法访问列表中的内容以将它们写入文件。我有另一个带键的列表,所以我可以访问名称。

ListKey = {1:'Food', 2:'Veggie'}
List={'Food':['apple','pear','grape'], 'Veggies':['carrot','Spinach','Potato']}

file.write(ListKey[1]) #works fine
currentList=ListKey[1]
file.write(List[currentList[1]]) #Doesn't Work

当我尝试执行上面的代码时,我得到一个关键错误,我知道它试图在食物中写入 'o'。有没有办法解决这个问题?

currentList[1]就是值o,使用:

file.write(List[currentList])

您似乎正在尝试访问密钥对中的值。尝试:

List[currentList][0] to access 'apple'
List[currentList][1] to access 'pear'

等...

或者,如果您想要所有值,它看起来像

List[currentList]  or 
List['Food']

希望这对您有所帮助,只是您如何访问内部列表的语法。

编辑: https://docs.python.org/2/tutorial/datastructures.html#nested-list-comprehensions (添加 link 到数据结构文档)

ListKey = {1:'Food', 2:'Veggie'} List={'Food':['apple','pear','grape'], 'Veggies': ['carrot','Spinach','Potato']} currentList = ListKey[1] #'Food' currentList[1] # 'o'

您实际上是在索引字符串 "Food"。因此 currentList[1] 是 'o'。由于 List 没有键 'o' 你会遇到键错误。