为什么钥匙被确定为价值?

时间:2013-08-02 15:00:46

标签: python dictionary

我正在使用理解来创建字典。该错误表示我的密钥存储为值而不是密钥。

以下是完整情况:

我的BLS数据如下所示:

O*NET-SOC Code  Element ID  Element Name    Scale ID    Data Value  N   Standard Error  Lower CI Bound  Upper CI Bound  Recommend Suppress  Not Relevant    Date    Domain Source
11-1011.00  1.A.1.a.1   Oral Comprehension  IM  4.5 8   0.19    4.13    4.87    N   n/a Jun-06  Analyst
11-1011.00  1.A.1.a.1   Oral Comprehension  LV  4.75    8   0.25    4.26    5.24    N   N   Jun-06  Analyst
11-1011.00  1.A.1.a.2   Written Comprehension   IM  4.38    8   0.18    4.02    4.73    N   n/a Jun-06  Analyst

并希望返回一个看起来像这样的结构,并为每个作业提供详细的级别数据(作业由SOC代码表示,数据的最左侧列。例如,作业的SOC代码下面的'职员'可能是11-1011.00)。

{
    'job':'clerk', 'description': 'works in a bank', 'abilities': {
        'math': [
            {
            'Scale ID': 'IM',
            'Data Value': 4.5,
            'N' : 8,
            'S_E': 0.19
            },
            {'Scale ID': 'LV',
            'Data Value': 4.75,
            'N': 8,
            'S_E': 0.25
            }        
        ]
        'english': [
            {
            'Scale ID': 'IM',
            'Data Value': 2,
            'N' : 8,
            'S_E': 0.19
            },
            {'Scale ID': 'LV',
            'Data Value': 3,
            'N': 8,
            'S_E': 0.25
            }        
        ]  
    }
},

为此,我在我的能力领域创建一个词典列表,并为每个能力创建一个级别(LV)和重要性(IM)数据列表。

当我为IM / LV词典创建字典时,会标记错误。

这是我的代码:

"""
Abilities
"""

# returns a list of dictionaries, each of the dictionaries representing a row in the data posted above with keys = top row and values = row vals.
abilities_m_l = create_abilities_master_list(file_list[0])    

# for each job (for each dictionary in the master list of job dictionaries)
for job in d_l:

    job_row = 1

    while job_row < 100: # just to test

        # initialize the list of abilities for the job
        job['abilities'] = []
        job['abilities'].append({abilities_m_l[job_row]['Element Name']:[]}) 

        while job['O*NET-SOC Code'] == abilities_m_l[job_row]['O*NET-SOC Code']:

            if abilities_m_l[job_row]['Element Name'] == abilities_m_l[job_row-1]['Element Name']:
                job[abilities_m_l[job_row]['Element Name']].append({key:value for key,value in abilities_m_l[job_row] if key not in ('O*NET-SOC Code','Element Name', 'Scale ID')})

            else:
                job[abilities_m_l[job_row]['Element Name']] = []
                job[abilities_m_l[job_row]['Element Name']].append({key:value for key,value in abilities_m_l[job_row] if key not in ('O*NET-SOC Code','Element Name', 'Scale ID')})

            job_row += 1   

    break           

for job in d_l:
    print job['abilities']

这是我的错误:

Traceback (most recent call last):
  File "/private/var/folders/jv/9_sy0bn10mbdft1bk9t14qz40000gn/T/Cleanup At Startup/bls-397147690.633.py", line 65, in <module>
    job[abilities_m_l[job_row]['Element Name']].append({key:value for key,value in abilities_m_l[job_row] if key not in ('O*NET-SOC Code','Element Name', 'Scale ID')})
KeyError: 'Oral Comprehension'
logout

2 个答案:

答案 0 :(得分:1)

您正在测试列表是否存在错误:

if abilities_m_l[job_row]['Element Name'] == abilities_m_l[job_row-1]['Element Name']:
    job[abilities_m_l[job_row]['Element Name']].append({key:value for key,value in abilities_m_l[job_row] if key not in ('O*NET-SOC Code','Element Name', 'Scale ID')})

这里假设只是因为前一行具有相同的元素名称,您将已经为该键添加了一个列表。显然,Oral Comprehension密钥的假设是错误的。

只需测试密钥:

key = abilities_m_l[job_row]['Element Name']
if key not in job:
    job[key] = []
job[key].append({key:value for key,value in abilities_m_l[job_row] if key not in ('O*NET-SOC Code','Element Name', 'Scale ID')})

您还可以使用dict.setdefault()让它返回列表值,或者如果尚未设置密钥则设置一个空列表值:

key = abilities_m_l[job_row]['Element Name']
job.setdefault(key, []).append({key:value for key,value in abilities_m_l[job_row] if key not in ('O*NET-SOC Code','Element Name', 'Scale ID')})

答案 1 :(得分:1)

您不能使用.append()附加到不存在的密钥。

考虑使用collections.defaultdict(以便不存在的键默认使用列表作为其值),或者使用列表初始化abilities_m_l [job_row] ['Element Name']或'job'。其中一个是尝试附加到一个不存在的密钥(如果密钥尚不存在,则会返回KeyError)

开始于:

from collections import defaultdict

job=defaultdict(list)

这将确保键默认为空列表,并允许您的代码工作。