簡體   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