Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

python 3.x - Doesn't add all elements that are not in dictionary values

I'm iterating over the list and supposedly add element to dictionary that doesn't occur in dictionary as value, therefore I would expect output:

{'key': 1, 'key2': 3, 'key3': 2, 'key4':4, 'key5':5}

Code:

di = {'key':1, 'key2':4}

li=[1,1,1,2,4,3,5]

b = sum(1 for key in di if key.startswith('key')) # check how many keys starts with 'key'

for i in li:                #if element of list is not in dictionary key values 
    if i not in di.values():  #add it as value to 'key+b+1'
        di[f'key{b+1}']= i

But the ouput I'm getting:

{'key': 1, 'key2': 4, 'key3': 5}

So as I see despite I'm telling Python to check elements in dict.values he's checking also keys or items.

question from:https://stackoverflow.com/questions/65849697/doesnt-add-all-elements-that-are-not-in-dictionary-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that after you add a new key to di, you don't increment the count b. Use the following to solve your problem:

for i in li:                #if element of list is not in dictionary key values 
    if i not in di.values():  #add it as value to 'key+b+1'
        di[f'key{b+1}']= i
        b += 1  

Which produces:

{'key': 1, 'key2': 4, 'key3': 2, 'key4': 3, 'key5': 5}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...