简体   繁体   English

如何使用Python在此字典中使用空字符串将值添加为缺少的键

[英]How to add the missing keys in this dictionary with values as empty string using python

the dictionary sample is as below : 字典样本如下:

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

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. 我想在键3之后添加键4,将空字符串作为值,在键7之后添加键8,将空字符串作为值,以此类推....我想要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 dictionaries do not maintain an order. Python字典不维护顺序。 You cannot add anything 'after' another key. 您不能在“其他”键之后添加任何内容。

Just add the keys you are missing: 只需添加您缺少的键:

d.update((missing, '') for missing in set(range(1, max(d) + 1)).difference(d))

which is a compact way of saying: 这是一种简洁的说法:

for index in range(1, max(d) + 1):  # all numbers from 1 to the highest value in the dict
    if index not in d:              # index is missing
        d[index] = ''               # add an empty entry

However, it looks more like you need a list instead: 但是,它看起来更像是您需要一个列表:

alist = [None, '', '', '', '', '', '2', '', '', '', '6', '7', '', '9', '', '11']

where alist[15] returns '11' just like your d . 其中alist[15]d一样返回'11' The None at the start makes it easier to treat this whit 1-based indexing instead of 0-based, you could adjust your code for that otherwise. 开始时使用None可以更轻松地处理这种基于1的索引,而不是基于0的索引,否则您可以调整代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM