如何使用python在此字典中添加缺失的键,值为空字符串 [英] How to add the missing keys in this dictionary with values as empty string using python

查看:37
本文介绍了如何使用python在此字典中添加缺失的键,值为空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字典示例如下:

d = { 1:'',2:'',3:'',5:'',6:'2',7:'',9:'',10:'6',11:'7',13:'9',14:'',15:'11'}

并且我想在键 3 之后添加带有空字符串的键 4 作为值,在键 7 之后添加带有空字符串的键 8 等等......我想要最简单的 Python 代码.

and i want to add key 4 with empty string as value after key 3, key 8 with empty string as value after key 7 and so on ....I want the simplest code in python.

推荐答案

>>> d = { 1:'',2:'',3:'',5:'',6:'2',7:'',9:'',10:'6',11:'7',13:'9',14:'',15:'11'}
>>> d.update(dict.fromkeys(set(range(16)).difference(d), ''))
>>> d
{0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '2', 7: '', 8: '', 9: '', 10: '6', 11: '7', 12: '', 13: '9', 14: '', 15: '11'}

注意字典无序的,即使它在这个例子中看起来是有序的!

Note that the dict is unordered, even though it may look ordered in this example!

这篇关于如何使用python在此字典中添加缺失的键,值为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆