如何为字典中的首字母创建多个词典?

时间:2018-06-16 09:38:40

标签: python list dictionary random

我想从列表中创建列表。在主要列表中,我有1300多个英语到西班牙语的词典单词(最常见)。例如:

words = {"hablar":"to speak","reir":"to laugh","comer":"to eat"}

和这样的1300多个单词。我不想手动将它们分隔为首字母。我想制作一个程序,像这样自动分离它们;

    a_words = {words with a}
    b_words = {words with b}
    c_words = {"comer":"to eat"}
    .
    .
    .
    .
    .
    h_words = {"hablar":"to speak"}

我的程序会自动为每个首字母创建字典。我会做一个随机选择功能所以当我运行程序时,它会显示一个西班牙语单词,我将用英语输入,所以我将练习。谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

通常,您可以使用压缩,例如:

a_words = {k:v for k,v in allwords.items() if k.lower().startswith('a')}

但是当然你会更好地拥有一本字典词典:

split_dicts = {L:{k:v for k,v in allwords.items() if k.lower().startswith(L)} for L in "abcdefghijklmnopqrstuvwxyz"}  
# May need to change the list of characters depending on language.

请注意,在早期的蟒蛇中,您可能需要使用上面的iter_items()而不是items()

为了清晰起见,扩展了第二次压缩:

split_dicts = dict()  # This will become a dictionary of dictionaries
for L in "abcdefghijklmnopqrstuvwxyz":  # Iterate the letters
    # May need to change the list of characters depending on language
    split_dict[L] = dict()  # Add a dictionary for this letter
    for k,v in allwords.items():  # Python 2 use .iter_items()
        if k.lower().startswith(L):  # If lowercase of the word starts with this letter
             split_dict[L][k] = v  # Add to the dictionary for this letter an entry for k

然后您可以使用随机:

import random
letter = random.choice('abcdefghijlkmnopqrstuvwxyz')
s_word = random.choice(list(split_dict[letter].keys()))
e_word = split_dict[letter][s_word]

答案 1 :(得分:0)

这是一种方法。使用collections.defaultdict

<强>演示:

import collections
words = {"hablar":"to speak","reir":"to laugh","comer":"to eat"}
d = collections.defaultdict(list)
for k,v in words.items():
    d[k[0].lower()].append({k: v})
print(d)

print("Words in H")
print(d["h"])

<强>输出:

defaultdict(<type 'list'>, {'h': [{'hablar': 'to speak'}], 'c': [{'comer': 'to eat'}], 'r': [{'reir': 'to laugh'}]})

Words in H
[{'hablar': 'to speak'}]