新手求助,关于python字典的问题
dict1={}dict1.fromkeys((1, 2, 3), ('one', 'two', 'three'))
print(dict1)
求助为什么打印结果还是空列表而不是{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')} 本帖最后由 昨非 于 2020-11-19 22:06 编辑
fromkeys 方法只用来创建新字典,不负责保存。当通过一个字典来调用 fromkeys 方法时,
如果需要后续使用一定记得给他复制给其他的变量。
>>> dict1={}
>>> dict1.fromkeys((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> print(dict1)
{}
>>> dict2=dict1.fromkeys((1,2,3),'number')
>>> dict2
{1: 'number', 2: 'number', 3: 'number'}
dict1={}
dict2=dict1.fromkeys((1, 2, 3), ('one', 'two', 'three'))
print(dict2)
输出结果就是:{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')} dict.fromkeys是静态方法哦不是实例来调用的 是直接类去调用的
页:
[1]