在python列表循环中访问第二个值

时间:2019-04-05 15:06:33

标签: python python-3.x

我正在尝试访问从json对象创建的列表中的第二个值。访问第一个值"name"时,我没有问题。但是当尝试访问"address"时出现错误

Result: Failure
Exception: KeyError: 'address' 

传入的json看起来像这样

{
  "DataToCompare": [
    {
        "name": "Alex Young",
        "address": "123 Main Street"
    }
  ],
  "DataSetAgainst": [
    {
        "name": "Bob Doll",
        "address": "555 South Street"
    },
    {
        "name": "Bob Young",
        "adress": "123 Main St."
    }
  ]
}

在下面的示例中dataBack["address"] = i["address"]是错误的出处。如果我将其注释掉,则会得到namename match的结果

def processing_request(dataIncoming):

    data_to_compare = dataIncoming["DataToCompare"][0]

    dataList = []
    for i in dataIncoming["DataSetAgainst"]:
        dataList.append(i)

    dataResults = []

    for i in dataList:
        dataBack = {}

        clean_name = ''.join(e for e in i["name"] if e.isalnum())
        sequence = difflib.SequenceMatcher(isjunk=None, a=data_to_compare["name"], b=clean_name)
        difference = sequence.ratio()*100
        difference = round(difference, 1)

        # works
        dataBack["name"] = i["name"]
        dataBack["name match"] = difference

        # doesnt work
        dataBack["address"] = i["address"]

        dataResults.append(dataBack)

    return json.dumps(dataResults)

2 个答案:

答案 0 :(得分:1)

该错误似乎是由错字引起的:

{
  "DataToCompare": [
    {
        "name": "Alex Young",
        "address": "123 Main Street"
    }
  ],
  "DataSetAgainst": [
    {
        "name": "Bob Doll",
        "address": "555 South Street"
    },
    {
        "name": "Bob Young",
        "address": "123 Main St."
    }
  ]
}

我解决了什么:"adress": "123 Main St.""address": "123 Main St."

在这种情况下共享的代码的输出:

'[{"name": "Bob Doll", "name match": 11.8, "address": "555 South Street"}, {"name": "Bob Young", "name match": 55.6, "address": "123 Main St."}]'

答案 1 :(得分:0)

从我看到的情况来看,该错误是由于a中的错误引起的。

"address": "123 Main St."

行。但是,让我们怀疑一下,并假设数据已损坏,我们希望找到解决方法。

我们可以通过以下方式将i值转换为值列表:

tab = []
for key in i:
    value = i[key]
    tab.append(value)

如果我们现在下达命令来打印标签,我们将获得输出:

['Bob Doll', '555 South Street']
['Bob Young', '123 Main St.']

因此,代替上面的解决方案,您可以将最后一行写为:

dataBack["name"], dataBack["address"] = tab
dataBack["name match"] = "cookies"

作为脚本的完整答案:

def processing_request(dataIncoming):

    data_to_compare = dataIncoming["DataToCompare"][0]

    dataList = []
    for i in dataIncoming["DataSetAgainst"]:
        dataList.append(i)

    dataResults = []

    for i in dataList:
        dataBack = {}

        clean_name = ''.join(e for e in i["name"] if e.isalnum())
        sequence = difflib.SequenceMatcher(isjunk=None, a=data_to_compare["name"], b=clean_name)
        difference = sequence.ratio()*100
        difference = round(difference, 1)

        tab = [i[key] for key in i]

        # works
        dataBack["name"], dataBack["address"] = tab
        dataBack["name match"] = difference

        dataResults.append(dataBack)

    return json.dumps(dataResults)