简体   繁体   中英

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

I want to create lists from a list. In the main list i have 1300+ dictionary words (most common) for English to Spanish. for example:

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

and 1300+ words like this. I do not want to seperate them manually for initials. I want to make a program to seperate them automatically like this;

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

my program will automatically create dictionaries per initial letters. And i will make a random selection function so when i run the program, it will show me a word in Spanish and i will type it in English so i will be practicing. Thanks for all your help.

In general you can use compressions such as:

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

But of course you would be better off having a dictionary of dictionaries with:

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.

Note in earlier pythons you may need to use iter_items() rather than items() in the above.

Expanding the second compression for clarity:

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

You can then use random:

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

This is one approach. Using collections.defaultdict

Demo:

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"])

Output:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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