我想修改字典鍵 我到了將字典的鍵更改為不知道如何處理的值的階段
[
]
問題)使用下面的串列創建字典
english_word_list = ['black', 'history', 'blood', 'campaign', 'image', 'kid', 'kill',
'can', 'eye', 'faceblue', 'camera', 'future', 'game', 'kind', 'kitchen']
指定英文單詞的第一個字母作為字典鍵。f 密鑰重復,將密鑰指定為英文首字母和數字的組合。
前任)
{'b': 'black', 'h': 'history', 'b2': 'blood', 'c': 'campaign', 'i': 'image',
'k': 'kid', 'k2': 'kill', 'c2': 'can',
'e': 'eye', 'f': 'faceblue', 'c3': 'camera',
'f2': 'future', 'g': 'game', 'k3': 'kind', 'k4': 'kitchen'}
uj5u.com熱心網友回復:
我猜您可能正在談論通過python進行編程。
這是您要求的問題的簡單解決方案
english_word_list = ['black', 'history', 'blood', 'campaign', 'image', 'kid', 'kill',
'can', 'eye', 'faceblue', 'camera', 'future', 'game', 'kind', 'kitchen']
dictionary = {} # create an empty dictionary for lookup
for word in english_word_list:
letter = word[0] # assume no empty words
key = letter
i = 2
while dictionary.get(key) is not None: # get will return None if no key is present
key = letter str(i)
i = 1
dictionary[key] = word # add the word with the free key
print(dictionary)
希望對您有所幫助,如果您覺得可以,請采納答案。
uj5u.com熱心網友回復:
您可以使用輔助字典來跟蹤到目前為止您看到的每個起始字母的數量,并根據計數添加適當的鍵。
import string
counters = dict.fromkeys(string.ascii_lowercase, 1)
result = {}
for word in english_word_list:
if counters[word[0]] == 1:
result[word[0]] = word
else:
result[f"{word[0]}{counters[word[0]]}"] = word
counters[word[0]] = 1
print(result)
這輸出:
{'b': 'black', 'h': 'history', 'b2': 'blood',
'c': 'campaign', 'i': 'image', 'k': 'kid', 'k2': 'kill',
'c2': 'can', 'e': 'eye', 'f': 'faceblue',
'c3': 'camera', 'f2': 'future', 'g': 'game',
'k3': 'kind', 'k4': 'kitchen'}
uj5u.com熱心網友回復:
雖然這看起來更復雜,但我認為您應該分兩次執行此操作:
ls = ['black',
'history',
'blood',
'campaign',
'image',
'kid',
'kill',
'can',
'eye',
'faceblue',
'camera',
'future',
'game',
'kind',
'kitchen']
# Group by first letter
dt = dict()
for i in ls:
letter = i[0]
lx = dt.get(letter, [])
lx.append(i)
dt[letter] = lx
print(dt)
# Enumerate keys based on group size
dx = dict()
for k, v in dt.items():
# For a given list, assign a key to each item
for idx, item in enumerate(v):
key = f"{k}{idx}" if idx > 0 else f"{k}"
dx[key] = item
print(dx)
第一個 for 回圈按第一個字母對所有單詞進行分組。print(dt)證明了這一點。這是一個有用的中間步驟,可確保您正確地做事。然后,在給定的情況下dt,我們可以dx輕松地構建您想要的結果——因為我們正在對類似專案的串列進行操作,而不是在整個原始字典上進行操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465153.html
