如何在Python中动态嵌套现有字典?

2024-05-26 07:47:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序可以要求用户对现有词典进行分类: 这是我的字典:

>>> print Vocab_World
{'excelent': 'awesome', 'quit': 'exit', 'great': 'good', 'ceken': 
'bilir', 'tremendous': 'fabolous', 'gurbet': 'hasret', 'postpone': 
'put_offt', 'ozlem': 'hasret'}

现在,我想问用户是否要将与嵌套字典相同的有意义的单词分类,我想为分类的单词创建一个如下所示的列表

{'Adverb' : {'excelent': 'awesome','great': 'good','tremendous': 'fabolous'} }

是的。你知道吗

categorized_words = raw_input("Please select the words that you want to categorize")
new_category = raw_input("Please input the new category name ")
categorized_World=Vocab_World[new_category][0][categorized_words]

有没有一种方法可以根据用户的输入动态地实现这一点?你知道吗


Tags: 用户newworldinput字典分类awesomegood
2条回答
Vocab_World = {'excelent': 'awesome', 'quit': 'exit', 'great': 'good', 'ceken': 
'bilir', 'tremendous': 'fabolous', 'gurbet': 'hasret', 'postpone': 
'put_offt', 'ozlem': 'hasret'}

Categorized_World = {}  # output dict
chosen_words = []       # array to store all the chosen words

while True:
    categorized_words = raw_input("Words to categorize separated by ',' or Q/q for quit)")
    if categorized_words.lower() == 'q':
        break
    chosen_words.extend(categorized_words.split(','))
    new_category = raw_input("Please input the new category name ")
    Categorized_World[new_category] = {i:Vocab_World[i] for i in
                                       categorized_words.split(',') if i in Vocab_World}

# Add words that are not catgorized
Categorized_World.update({i:Vocab_World[i] for i in Vocab_World if i not in chosen_words})

print(Categorized_World)

运行并输入:

excelent,great,tremendous
adverb
q

将返回:

{'adverb': {'excelent': 'awesome', 'great': 'good', 'tremendous': 'fabolous'}, 
'quit': 'exit', 'ceken': 'bilir', 'gurbet': 'hasret', 
'postpone': 'put_offt', 'ozlem': 'hasret'}

这应该做到:

Vocab_World= {'excelent': 'awesome', 'quit': 'exit', 'great': 'good', 'ceken': 
              'bilir', 'tremendous': 'fabolous', 'gurbet': 'hasret', 'postpone': 
              'put_offt', 'ozlem': 'hasret'}

categorized_words = raw_input("Please select the words that you want to categorize ")
new_category = raw_input("Please input the new category name ")

Categorized_World=dict()
tmp=dict()
for w in categorized_words.split():
  tmp.update({w:Vocab_World[w]})

Categorized_World.update({new_category:tmp})
print Categorized_World

输出为:

Please select the words that you want to categorize excelent great tremendous
Please input the new category name Adverb
{'Adverb': {'excelent': 'awesome', 'tremendous': 'fabolous', 'great': 'good'}}

相关问题 更多 >