Remove from Python Dictionary

Asked 2 years ago, Updated 2 years ago, 135 views

w_count={}

lists=["Night", "Smile", "Joke", "Dawn", "Dawn", "Crying", "Smile"]

for i in lists:

    try: w_count[i]+=1

    except: w_count[i]=1


for i in w_count:

    if w_count.get(i)==1:

        w_count=w_count.pop(i)


print (w_count)

Displays the number of duplicate times in the list, stores them in a dictionary, and if the index value in the dictionary is 1, you want to remove them and print them out. So I used pop() and when I activated it, it said that the dictionary's length has changed, so it cannot be printed. How can I solve this problem?

python dictionary

2022-09-22 19:14

1 Answers

w_count={}

lists=["Night", "Smile", "Joke", "Dawn", "Dawn", "Crying", "Smile"]

for i in lists:

    try: w_count[i]+=1

    except: w_count[i]=1

#print (w_count)

keys = list(w_count.keys())        
for i in keys:
    if w_count.get(i)==1:
        w_count.pop(i)


print (w_count)


2022-09-22 19:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.