【问题标题】:Error when trying to access an item in a for loop尝试访问 for 循环中的项目时出错
【发布时间】:2021-11-27 05:24:28
【问题描述】:

大家好,我正在尝试获取一个值,如果它等于循环遍历项目的字符串。但我收到错误“字典条目必须包含键/值对”,我不知道如何解决。我是 python 编程的新手,我正在努力寻找应该如何完成的信息。我用的是python3.x 我的代码是这样的

        for index, debtor in enumerate(case.get_debtors):
        if debtor.type==1:
            context = {
                "recipientName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''),
                "debtorRole": "Длъжник",
                "debtorAddress": debtorAddress,
                "publicExecutorDefaultBankAccount": "ygvyvb",
                "courtStaff": f"{case_details.systav}".replace('None', ''),
                "courtName": f"{case_details.courtName}".replace('None', ''),
                "archNumber": case.id,
                "debtorName": f"{debtor.first_name} {debtor.middle_name} {debtor.last_name}".replace('None', ''),
                "creditorName": f"{creditor.first_name} {creditor.middle_name} {creditor.last_name}".replace('None', ''), #creditor.type==2
                "creditorAddress": creditorAddress,
                "executionListDate": executionListDate,
                "exListIdentifier": exListIdentifier,
                "amount": amount,
                "amountDate": amountDate,
                "agreementInterest": agreementInterest,
                "penaltyInterest": penaltyInterest,
                "expences": expences,
                "taxPublicExecutor": taxPublicExecutor,
                "brokerage": brokerage,
                "measuresSum": measuresSum,
                if debtor(index).postcode1=="1000":
                    "recipientNameNAP": "ТД НА НАП – СОФИЯ",
                    "recipientAddressNAP": "Адрес: ул.„Аксаков” № 21 1000 София",

                "BASE_DIR": f"{settings.BASE_DIR}".replace("""\\""", "/"),

            }

请帮助我。我知道这很简单,但我找不到解决方案

【问题讨论】:

  • 您确定可以在字典初始化程序中包含if 语句吗?看起来您在 for 循环下的 if 语句应该再缩进一级。
  • 我需要 if 语句,因为这些字符串会根据邮政编码而有所不同
  • 然后在字典初始值设定项之外计算if部分并只使用里面的结果。
  • 这不是一个选项,因为我必须在每个 if 和 elif 语句中使用整个上下文。有 49 种变化
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python-3.x django


【解决方案1】:
{
...
            if debtor(index).postcode1=="1000":
                "recipientNameNAP": "ТД НА НАП – СОФИЯ",
                "recipientAddressNAP": "Адрес: ул.„Аксаков” № 21 1000 София",

...
}

问题是您不能在{ ... } 中包含if 来初始化字典。您将不得不为您的问题找到不同的解决方案。

一种可能的解决方案是像您已经做的那样构建大部分字典,然后在词后添加if 语句以将任何其他键和值添加到字典中。

【讨论】:

  • 你能推荐一个吗?
  • @ParantarNakirar 刷新页面以查看我的编辑。
  • 以及如何将新语句附加到我的上下文中?
  • @ParantarNakirar 需要明确的是,您不能将语句附加到字典中。这甚至没有意义。相反,您将值分配给键。您当前的 { ... } 语法只是一次将一堆值分配给一堆键的快捷方式。如果您不知道如何为 dict 中的键分配值,那么我建议您 google 并阅读它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2014-02-23
  • 1970-01-01
  • 2023-03-13
  • 2012-07-06
  • 1970-01-01
相关资源
最近更新 更多