簡體   English   中英

Python:編輯字典鍵 - 使用剝離方法

[英]Python: Editing Dictionary Keys - Using Strip Method

我有一本字典,如下所示:

Dict = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

我想編輯每個條目的鍵,而不是值。 您可以看到的鍵有一個字符串,其中包含開頭和結尾的空格: ' Chicago '、' Washington '、' LA '

我想分組並從鍵中去除空白。 給我留下以下字典。

Dict = {'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

我該怎么做? 也許使用replace(" ", "")方法或strip()

嘗試 strip 方法時出現錯誤:

AttributeError: 'int' object has no attribute 'strip'

您的錯誤表明您嘗試轉換值而不是鍵,但無論如何,這應該有效:

new_dict = {key.strip(): value for key, value in old_dict.items()}

使用dict理解:

  • 順便說一句,不要使用 python 數據類型作為變量的名稱(例如Dict
  • 聽寫理解
  • 遍歷字典時,可以使用.items()方法同時檢索key和對應的value
  • .strip只在key
data = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

data = {k.strip(): v for (k, v) in data.items()}

>>> {'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

最簡單的方法是:

Dict2 = {}
for key in Dict:
   Dict2[key.strip()] = Dict[key]
Dict = Dict2

或者您可以使用理解來緩解它:

Dict = {key.strip():value for (key,value) in Dict}

我認為最簡單的方法是循環鍵,如下所示。 我一路上對代碼進行了評論。

#Your dictionary
dict = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

#Puts all keys of the dictionary into a list
keys = list(dict)

#iterates over dictionary keys
for key in keys:

    #for every key, we make a new dictionary item with the 'stripped' key and remove the old one
    dict[key.strip()] = dict[key]
    del dict[key]

print(dict)

這為我們提供了相同的字典和相同的值,但從鍵中刪除了前導/尾隨空格:

{'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

您不能直接編輯鍵,因為字典是 hash 表。 更改密鑰會更改其 hash,因此您有兩個概念選項。

首先是替換整個字典,在我看來這更pythonic:

dct = {k.strip(): v for k, v in dct.items()}

或者:

dct = {k.strip(): dct[k] for k in dct}

第二種選擇是保留相同的字典 object,但將映射一一替換。 由於在迭代字典時不應該修改鍵,尤其是在刪除時,這使情況變得復雜。 您必須先制作原始密鑰的單獨副本並使用它:

for k in list(dct):
    v = dct.pop(k)
    dct[k.strip()] = v

暫無
暫無

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

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