首页 > 解决方案 > 为什么我在 Python3.6 中无法获取字典的键列表?

问题描述

我正在学习 Python。我试图获取字典的键。但我只得到最后一个钥匙。据我了解,keys() 方法用于获取字典中的所有键。

以下是我的问题?

1. Why I cannot get all keys? 
2. If I have a dictionary, how can I get the value if I know the key? e.g. dict = {'Ben':8, 'Joe':7, 'Mary' : 9}. How can I input the key = "Ben", so the program can output the value 8? The tutorial shows that the key must be immutable. This constraint is very inconvenient when trying to get a value with a given key. 

任何建议将不胜感激。

这是我的代码。

import os, tarfile, urllib

work_path = os.getcwd()
input_control_file = "input_control"
import os, tarfile, urllib

work_path = os.getcwd()
input_control_file = "input_control"
input_control= work_path + "/" + input_control_file

#open control file if file exist
#read setting info
try:
   #if the file does not exist,
   #then it would throw an IOError
   f = open(input_control, 'r')

   #define dictionary/hash table
   for LINE in f:
      LINE = LINE.strip()     #remove leading and trailing whitespace
      lst = LINE.split()      #split string into lists
      lst[0] = lst[0].split(":")[0]
      dic = {lst[0].strip():lst[1].strip()}

except IOError:
   # print(os.error) will <class 'OSError'>
   print("Reading file error. File " + input_control + " does not      exist.")

#get keys
def getkeys(dict):
   return list(dict.keys())
print("l39")
print(getkeys(dic))
print("end")

下面是输出。

l39
['source_type']
end

标签: python-3.xdictionarykey

解决方案


原因是您dic在 for 循环中再次重新分配变量。您没有更新或添加字典,而是重新分配变量。在这种情况下,dic将只有最后一个条目。您可以将for循环更改为:

dic = {}
for LINE in f:
    LINE = LINE.strip()     #remove leading and trailing whitespace
    lst = LINE.split()      #split string into lists
    lst[0] = lst[0].split(":")[0]
    dic.update({lst[0].strip():lst[1].strip()}) # update the dictionary with new values.

对于您的其他问题,如果您有 dictionary dic = {'Ben':8, 'Joe':7, 'Mary' : 9},那么您可以通过以下方式获取值:dic['Ben']。如果在字典中找不到键,它将返回值8或引发。为了避免,你可以使用字典的方法。如果在字典中找不到提供的键,它将返回。KeyErrorBenKeyErrorget()None

val = dic['Ben'] # returns 8
val = dic['Hen'] # will raise KeyError
val = dic.get('Hen') # will return None

推荐阅读