【问题标题】:Why I cannot get the key list of a dictionary in Python3.6?为什么我在 Python3.6 中无法获取字典的键列表?
【发布时间】:2020-02-12 05:11:09
【问题描述】:

我正在学习 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.x dictionary key


    【解决方案1】:

    原因是您在 for 循环中再次重新分配变量 dic。您没有更新或添加字典,而是重新分配变量。在这种情况下,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.
    

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

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

    【讨论】:

    • 感谢您的回答。我仍然无法获得所有钥匙。有什么建议吗?
    • 另外,当我给 key="Ben" 时,我什么也得不到。有什么原因吗?
    • 你能确认所有键都有不同的值吗?键应该是唯一的,如果有多个同名的键,则只使用最后一个键。
    • 如果密钥可用,您不应该得到None。也不要使用像dict这样的保留关键字,使用其他变量名
    • 是的。我得到了它。不正确的缩进导致了我的错误。衷心感谢您的帮助和时间。
    【解决方案2】:

    在您的 for 循环中,您正在重新初始化字典值,同时您需要更新字典,即将键值对附加到预先存在的字典中。为此,使用 dic.update({lst[0].strip() : lst[1].strip()}) 这会将键值对更新到字典中。现在,当您使用dic.keys() 时,您将获得dic 的所有键,作为一个列表。

    关于第二个问题,访问字典,就像访问列表一样,只是列表是通过索引访问的,而字典将通过键访问。比如说,你有一个列表和一个字典

    lst = [1, 2, 3, 4, 5]
    dic = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5}
    

    要从列表中获取值 2,请执行 lst[1],即索引 1 处的值。类似地,如果要从字典中获取值 2,请执行 dic['b'],即键“b”的值。就这么简单。

    【讨论】:

      猜你喜欢
      • 2022-06-29
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 2019-03-27
      • 1970-01-01
      • 2013-08-29
      相关资源
      最近更新 更多