python字典中的有效占位符

guykilcj  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(472)

我有一本字典,里面有整数值和字符串值。这些键的数字增加到n,但包含间隙。是否有一种有效的方法来填补特定数量的所有缺口(计算从1开始,而不是从0开始)
例子:

{1: "fdkh", 3: "wnww", 4: "fdngfne", 5: "wqiw", 7: "sdfsdf"}
 N = 9

结果应该是:

{1: "fdkh", 3: "wnww", 4: "fdngfne", 5: "wqiw", 7: "sdfsdf", 2: "placeholder", 6: "placeholder", 8: "placeholder", 9: "placeholder"}

当然我可以手动循环,但是有没有更聪明的方法呢?

63lcw9qa

63lcw9qa1#

一个快速的方法是

mydict = dict.fromkeys(range(1,N+1),"placeholder") | {
    1: "fdkh", 3: "wnww", 4: "fdngfne", 5: "wqiw", 7: "sdfsdf"}

虽然我怀疑你可能是想 collections.defaultdict :

mydict = defaultdict(lambda: "placeholder",{
    1: "fdkh", 3: "wnww", 4: "fdngfne", 5: "wqiw", 7: "sdfsdf"})

相关问题