d = {}.fromkeys(range(1,6),"one")
print(d)
如何为每个键分配一个不同的值?
具体来说:我要{1:"One",2:"Two", 3:"three", 4:"four", 5:"five"}
。
如果我使用fromkeys()
可以这样做吗?
答案 0 :(得分:2)
否,.fromkeys()
旨在添加具有单个默认值的键。
使用seq中的键并将值设置为value创建一个新字典。
fromkeys()
是返回新字典的类方法。值 默认为None
。
对于您的用例,您可能只需要“压缩”并成对制作字典:
In [1]: dict(zip(range(1, 6), ["One", "Two", "three", "four", "five"]))
Out[1]: {1: 'One', 2: 'Two', 3: 'three', 4: 'four', 5: 'five'}