其他值不显示在python字典中

时间:2017-11-19 04:13:00

标签: python dictionary

我正在编写一个程序来在python中创建一个字典,关键是单词的长度,值将是单词本身。因此,如果我在"中说出像#34;和"到",我希望字典打印dict_value = {2:[" in"," to"]}。为了进一步澄清我的问题,我的代码是:

string_value = "I ate a bowl of cereal out of a dog bowl today."
remove_p = string_value.replace(".","")
remove_c = remove_p.replace(",","")
remove_q = remove_c.replace("?","")
remove_e = remove_q.replace("!","")
remove_a = remove_e.replace('\'',"")
lowervalue = remove_a.lower()
split_v = lowervalue.split()
length = {}
for i in split_v:  
   length[len(i)] = []
   length[len(i)].append(i)         
print length

这是我的代码正在打印的内容:

{1: ['a'], 2: ['of'], 3: ['dog'], 4: ['bowl'], 5: ['today'], 6: ['cereal']}

这就是我想要打印的内容:

{1: ['i', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 5: ['today'], 6: ['cereal']}

因此,如果一个单词具有相同的长度,则应该在相同的键下打印。 感谢您的帮助。这个问题是关于在一个键下显示相同长度的单词,并且不涉及重构。我已经回顾了类似的问题,但没有完全适合我的。它们太先进或太基础

2 个答案:

答案 0 :(得分:0)

您可以使用if语句替换length[len(i)] = [],以防止在每次执行循环时执行它:

   if len(i) not in length.keys():
       length[len(i)] = []

效率不高,但答案很简单。

答案 1 :(得分:0)

这种问题存在一种模式:

让我们分两步解决您的问题:

  

首先split()字符串:

for item in string_value.split():
  

第二步就是遵循这种模式:

for item in string_value.split():
    if len(item) not in final_dict:
        final_dict[len(item)]=[item]
    else:
        final_dict[len(item)].append(item)
  

最终代码:

string_value = "I ate a bowl of cereal out of a dog bowl today."
final_dict={}
for item in string_value.split():
    if len(item) not in final_dict:
        final_dict[len(item)]=[item]
    else:
        final_dict[len(item)].append(item)

print(final_dict)

输出:

{1: ['I', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 6: ['cereal', 'today.']}
  

如果我们有:

string_value = "I ate a bowl of cereal out of a dog bowl today."
from collections import defaultdict

new_dict=defaultdict(list)
  

然后一行apporach:

[new_dict[len(item)].append(item) for item in string_value.split()]
print(new_dict)