【问题标题】:How can i create multiple dictionaries for initial letters from a dictionary?如何为字典中的首字母创建多个字典?
【发布时间】:2018-06-16 09:38:40
【问题描述】:

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

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

【问题讨论】:

  • 你卡在哪里了?你知道如何:(1)循环遍历字典(2)向字典添加元素吗? (请注意,制作 26 个变量是个坏主意,请改用 dict)
  • 你试过什么没用?
  • 目前尚不清楚您是否有包含所有单词的字典或列表。在示例中,您向我们展示了一本字典,但您将其称为“主列表”。请说清楚。
  • 我有一个单词 txt 文件,里面还有 1300 多个单词。我会将它们放在字典、列表或元组中,我什至不知道其中哪一种是创建程序的正确技术。我不想手动放置自定义列表/ dics。我想将它们全部放在同一个列表/字典中,并使用代码将它们放在自定义列表/字典中作为首字母。我该怎么做?

标签: python list dictionary random


【解决方案1】:

一般而言,您可以使用以下压缩方式:

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.

请注意,在早期的 python 中,您可能需要使用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]

【讨论】:

  • 感谢您的建议。我想我会用第一种方法来做,因为我不明白第二种方法。但是我想问另一个问题,如果我使用第一个代码,我可以随机选择单词吗?我的意思是我将为每个字母编写一个随机选择函数。所以我可以选择我想练习的字母。
  • @ArdaAltun 我扩大了我的答案,使第二个选项更清晰,并展示你如何使用它。
  • 非常感谢您的帮助!!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2021-05-15
    • 2013-04-23
    • 1970-01-01
    相关资源
    最近更新 更多