在python中从字典中删除键

时间:2019-02-28 12:30:15

标签: python-3.x list dictionary

def length_words(new):
    a = ",.!?'"
    for a in new:
        b = new.replace(a,"")
    b = b.lower()
    b = b.split()

    d = []
    for i in b:
        c = len(i)
        d.append(c)
    d.sort()
    e = d[-1]
    f = d[0]

    new2 = {}
    for i in range(f,e+1):
        new2[i] = []
    for i in range(1,e+1):
        for j in b:
            if len(j) == i:
                new2[i].append(j)

    for word in new2:
        if len(new2[word]) == 0:
            del new2[word]
    return new2

print(length_words(“如果我不喜欢某些东西,我会远离它。”))

解决方案必须具有以下词典:{1:['i'],2:['if','it'],4:['like','i'll','stay','away ','from'],5:['do n't],9:['something']}
我已经完成了该程序,但是当我尝试运行时,它显示 “ RuntimeError:字典在迭代过程中更改大小”
hpw我要删除带有空白列表的密钥吗?

2 个答案:

答案 0 :(得分:1)

之所以会出现此错误,是因为您无法在重复字典键时从字典中删除键。我用dict理解替换了函数中的最后一个块。

def length_words(new):
    a = ",.!?'"
    for a in new:
        b = new.replace(a,"")
    b = b.lower()
    b = b.split()

    d = []
    for i in b:
        c = len(i)
        d.append(c)
    d.sort()
    e = d[-1]
    f = d[0]

    new2 = {}
    for i in range(f,e+1):
        new2[i] = []
    for i in range(1,e+1):
        for j in b:
            if len(j) == i:
                new2[i].append(j)
    # Create a new dict that has only the keys with a value that its length is bigger than 0
    new2 = {k: v for k, v in new2.items() if len(v) > 0}
    return new2

答案 1 :(得分:0)

尝试一下:-

def length_words(new):
    a = ",.!?'"
    for a in new:
        b = new.replace(a,"")
    b = b.lower()
    b = b.split()

    d = []
    for i in b:
        c = len(i)
        d.append(c)
    d.sort()
    e = d[-1]
    f = d[0]

    new2 = {}
    for i in range(f,e+1):
        new2[i] = []
    for i in range(1,e+1):
        for j in b:
            if len(j) == i:
                new2[i].append(j)

    for word in list(new2.keys()):
        if len(new2[word]) == 0:
            del new2[word]
    return new2

遍历字典时,不允许删除或插入。
为此,您需要先获取密钥,然后使用这些密钥对字典进行遍历,这是使用list(new2.keys())

完成的