簡體   English   中英

無法將字符串附加到字典鍵

[英]Cannot append string to dictionary key

我已經進行了不到四個星期的編程,卻遇到了一個我無法解決的問題。 我試圖將一個字符串值附加到存儲有現有字符串的現有鍵中,但是如果該鍵中已經存在任何值,我會得到“ str對象沒有屬性'append'。

我試過將值轉換為list,但這也不起作用。 我需要使用.append()屬性,因為更新僅替換了clientKey中的值,而不是附加到已經存儲的任何值上。 經過更多研究后,我現在知道我需要以某種方式拆分存儲在clientKey中的值。

任何幫助將不勝感激。

data = {}

while True:

    clientKey = input().upper()
    refDate = strftime("%Y%m%d%H%M%S", gmtime())
    refDate = refDate[2 : ]
    ref = clientKey + refDate

    if clientKey not in data:
        data[clientKey] = ref

    elif ref in data[clientKey]:
        print("That invoice already exists")

    else:
        data[clientKey].append(ref)

        break

您不能.append()到字符串,因為字符串是不可更改的。 如果您希望字典值能夠包含多個項目,則它應該是一個容器類型,例如列表。 最簡單的方法是首先將單個項目作為列表添加。

if clientKey not in data:
    data[clientKey] = [ref]   # single-item list

現在您可以data[clientkey].append()進行data[clientkey].append()

解決此問題的一種簡單方法是使用collections.defaultdict 當項目不在時,它將自動創建該項目,從而使您的代碼更加簡單。

from collections import defaultdict

data = defaultdict(list)

# ... same as before up to your if

if clientkey in data and ref in data[clientkey]:
    print("That invoice already exists")
else:
    data[clientKey].append(ref)

您以字符串值開頭,並且無法在字符串上調用.append() 從列表值開始:

if clientKey not in data:
    data[clientKey] = [ref]

現在, data[clientKey]引用其中包含一個字符串的列表對象。 列表對象確實具有append()方法。

如果要繼續追加到字符串,則可以使用data[clientKey]+= ref

暫無
暫無

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

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