python-3.x - 不添加所有不在字典值中的元素
问题描述
我正在遍历列表,并且应该将元素添加到字典中,而字典中没有作为值出现,因此我希望输出:
{'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 中的元素,但他也在检查键或项目。
解决方案
您的问题是,在向 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}
推荐阅读
- artificial-intelligence - 在 CNN 中实现混合粒子群优化?(并且,关于整个算法的一般问题)
- solr - Solr 服务正在运行,但连接被 Ubuntu 20.04 上的 Solr 8.7.0 拒绝
- sql - 雪花更新语法
- unreal-engine4 - 找不到“生成 Visual Studio 项目文件”的选项
- python - 什么是启用按 Enter 键退出循环的正则表达式(Python)?
- mysql - 如何根据MYSQL中的条件求和
- flutter - Flutter video_player 多个视频
- apache-spark - 如何在独立模式下为 spark worker 配置 python 路径?
- google-sheets - 谷歌表格我如何使用获取单元格值,在另一个选项卡中搜索它,当找到匹配项时,抓取所有行?
- r - 无法从意外符号从 GitHub 下载包