python-3.x - 为什么我在 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
解决方案
原因是您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
或引发。为了避免,你可以使用字典的方法。如果在字典中找不到提供的键,它将返回。KeyError
Ben
KeyError
get()
None
val = dic['Ben'] # returns 8
val = dic['Hen'] # will raise KeyError
val = dic.get('Hen') # will return None
推荐阅读
- javascript - 尝试根据不带 jQuery 的更改重置选择选项
- javascript - 如何在 Vue 中转发 $refs
- actionscript-3 - 有人能告诉我为什么这段代码将框向左移动而不向右移动吗?AS3
- swift - 移除 NSOutlineView 周围的边框
- javascript - 如何仅选择父标签并更改其属性而不影响其在javascript中的子标签
- python-3.x - 使用 BaseUserAdmin 扩展我的默认用户模型后,我的信号停止工作
- ios - RXSwift 未订阅主线程
- python - 在python中,a是什么意思
是
if a[start] <= target < a[mid]
一样的a[start] <= target and target<a[mid] and a[start] < a[mid]
吗?(我认为不是,但在视觉上看起来两者是相同的)这在引擎盖下是如何工作的?在 SO 上搜索,但找不到答案。 - python - Python/Openpyxl 使用公式复制和粘贴列
- android - Firebase 实时数据库通过电子邮件通知触发 android