Rajesh Anand10
Rajesh Anand10

Reputation: 7

To remove the key from dictionary in python

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("If I don’t like something, I’ll stay away from it."))

The solution must have the dictionary : {1: ['i'], 2: ['if', 'it'], 4: ['like', 'i’ll', 'stay', 'away', 'from'], 5: ['don’t'], 9: ['something']}
I have done the program for that, but when i try to run, it displays "RuntimeError: dictionary changed size during iteration"
Hpw do i delete the key with the empty list?

Upvotes: 0

Views: 31

Answers (2)

Try this:-

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

Deletion or insertions are not allowed when you are iterating through dictionary.
To do this you need to get the keys first and then iterate through the dictionary using these keys which was done using list(new2.keys())

Upvotes: 0

Ohad Chaet
Ohad Chaet

Reputation: 519

You get this error because you cannot delete keys from a dictionary while iterating on its keys. I replaced the last block in your function with a dict comprehension.

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

Upvotes: 1

Related Questions