首页 > 解决方案 > 不添加所有不在字典值中的元素

问题描述

我正在遍历列表,并且应该将元素添加到字典中,而字典中没有作为值出现,因此我希望输出:

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

代码:

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

但我得到的输出:

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

因此,正如我所看到的,尽管我告诉 Python 检查 dict.values 中的元素,但他也在检查键或项目。

标签: python-3.xdictionary

解决方案


您的问题是,在向 di 添加新键后,您不会增加计数 b。使用以下方法解决您的问题:

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  

产生:

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

推荐阅读