簡體   English   中英

Python 中的嵌套字典問題(KeyError)

[英]Problem with nested Dict in Python (KeyError)

我嘗試將 append 數據轉換為 Python 中的復雜字典。
結構已給出,我無法更改。

示例代碼:

class AutoVivification(dict):
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

class Command(BaseCommand):

    def vorgang(self, lead):

        payload = AutoVivification()

        payload['antragsteller1'] = {
            'personendaten': {
                'anrede': lead.salutation,
                'vorname': lead.firstname,
                'nachname': lead.lastname,
                'email': lead.email,
                'telefonPrivat': lead.phone,
                'geburtsdatum': str(lead.birthdate)
            },
            'wohnsituation': {
                'anschrift': {
                    'strasse': lead.address,
                    'plz': lead.zip,
                    'ort': lead.city
                }
            },
            'beschaeftigung': {
                'beschaeftigungsart': lead.employment
            }
        }


        if lead.employment == 'ARBEITER':
            payload['antragsteller1']['beschaeftigung']['arbeiter']['beschaeftigungsverhaeltnis']['nettoeinkommenMonatlich'] = str(lead.income)

        elif lead.employment == 'ANGESTELLTER':
            payload['antragsteller1']['beschaeftigung']['angestellter']['beschaeftigungsverhaeltnis']['nettoeinkommenMonatlich'] = str(lead.income)

        elif lead.employment == 'ARBEITSLOSER':
            payload['antragsteller1']['beschaeftigung']['arbeitsloser']['sonstigesEinkommenMonatlich'] = str(lead.income)

錯誤:

KeyError: 'angestellter'

為什么 append 'angestellter' 在第二個 elif 語句中是不可能的?
這怎么可能?

payload['antragsteller1']['beschaeftigung']['angestellter']['beschaeftigungsverhaeltnis']['nettoeinkommenMonatlich'] = str(lead.income)

這個說法其實是:

some_dict = payload['antragsteller1']['beschaeftigung']['angestellter']['beschaeftigungsverhaeltnis']
some_dict['nettoeinkommenMonatlich'] = str(lead.income)

因此,在設置最后一個值之前,您正在檢索不存在的現有鍵值對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM