繁体   English   中英

字典无法调用键

[英]python - dictionary can't call key

这是我第一次在python中使用字典,我不确定输出是否正确,因为它与我在此处和示例中看到的其他结果不同。

我正在尝试用for循环填充字典:

data = {}
i=0

for fe in all_files:
    hdf_file = gdal.Open(workdir1 + "/" + fe)
    subDatasets = hdf_file.GetSubDatasets()
    Emissiv_Bands = gdal.Open(subDatasets[2][0])
    Bands = Emissiv_Bands.ReadAsArray()
    L_B_1 = radiance_scales[specific_band_1] * (Bands[specific_band_1] - radiance_offsets[specific_band_1])
    get_name_tag = re.findall(".A(\d{7}).", all_files[i])
    data ['%s' % get_name_tag] = L_B_1
    i=i+1

with open(workdir1 + "/data_dic.txt", "w") as f1:
    for x,y in data.items():
        print >> f1, x,y
f1.close()

该代码将打开具有特定名称的文件,并从中检索某些数据。 L_B_1只是单位转换。

所以在这一行:

data ['%s' % get_name_tag] = L_B_1

我正在尝试用名称标签作为键,然后是L_B_1的值来填充字典。 下面的打印文件代码产生以下输出:

['2018034'] [[ 8.92065776  8.90764162  8.91219727 ...,  8.07265598  8.07265598
   8.07330679]
 [ 8.89202225  8.8698948   8.85232301 ...,  8.0648463   8.0648463
   8.0739576 ]
 [ 8.8874666   8.85687866  8.80936973 ...,  8.07916405  8.07916405
   8.07916405]
 ..., 
 [ 2.43015756  1.97068768  1.78585843 ...,  7.58194735  7.6489805
   7.68477489]
 [ 2.36898168  1.94986185  1.73444466 ...,  7.586503    7.65418695
   7.68152086]
 [ 2.3709341   2.02079983  1.79757296 ...,  7.58845543  7.65548857
   7.67371117]]
['2018194'] [[  7.2610994    6.40789117   5.49936431 ...,   7.96722522   7.90084288
    7.93208163]
 [  7.35741887   6.46451139   5.54557163 ...,   7.98089217   7.96332037
    7.95420907]
 [  7.35741887   6.50421063   5.69265405 ...,   7.98284459   7.97373329
    7.97373329]
 ..., 

现在尝试仅打印第一个值:

print data['2018034']

我越来越:

  Traceback (most recent call last):
      File "MODIS_Plot.py", line 108, in <module>
        print data['2018034']
    KeyError: '2018034'

这是为什么? 为什么没有其他页面上显示的格式:

>>Output
{'iphone 3G': 2008, 'iphone 4S': 2011, 'iphone 3GS': 2009, '
    iphone': 2007, 'iphone 5': 2012, 'iphone 4': 2010}

我是否必须将:放在按键后面?

data键来自get_name_tag ,其值来自re.findall方法的结果,该方法返回正则表达式中带有1个捕获组的匹配子字符串的列表,这就是为什么get_name_tag作为列表转换为['2018034']格式为'%s' % get_name_tag

更改:

get_name_tag = re.findall(".A(\d{7}).", all_files[i])

至:

get_name_tag = re.findall(".A(\d{7}).", all_files[i])[0]

并且您的代码将按预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM