繁体   English   中英

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

[英]How can i create multiple dictionaries for initial letters from a dictionary?

我想从列表创建列表。 在主要列表中,我有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"}

我的程序将根据每个首字母自动创建字典。 而且我将执行随机选择功能,因此当我运行该程序时,它将向我显示一个西班牙语单词,然后将其输入英语,因此我将继续练习。 感谢你的帮助。

通常,您可以使用以下压缩:

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()您可能需要使用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

然后,您可以使用random:

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

这是一种方法。 使用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'}]

暂无
暂无

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

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