繁体   English   中英

如何将字典键修改为列表中单词的第一个字母?

[英]How do modify the dictionary key to the first letter of the word in the list?

我想修改字典键我去了我将字典键更改为一个值的阶段我不知道如何处理它

[在此处输入图像描述 ]

问题)使用下面的列表创建一个字典

english_word_list = ['black', 'history', 'blood', 'campaign', 'image', 'kid', 'kill',
                        'can', 'eye', 'faceblue', 'camera', 'future', 'game', 'kind', 'kitchen']

指定英文单词的第一个字母作为字典键。 如果密钥重复,请将密钥指定为英文首字母和数字的组合。

前任)

{'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'}

我猜你可能正在谈论通过 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)

您可以使用辅助词典来跟踪您到目前为止看到的每个起始字母的数量,并根据计数添加适当的关键字。

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'}

虽然这看起来更复杂,但我认为您应该分两次执行此操作:

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 - 因为我们正在对相似项目的列表进行操作,而不是对整个原始字典进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM