python字典fromkeys()方法中的坑
-
自定操作中的fromkeys()方法接收两个参数,第一个参数为一个可迭代对象,作为返回字典的key,第二个参数为value,默认为None,具体用法如下:
li = [1,2,3] dic1 = dict.fromkeys(li) dic2 = dict.fromkeys(li,[]) print(dic1) # {1: None, 2: None, 3: None} print(dic2) # {1: [], 2: [], 3: []}
-
此时我为dic2中key为1的列表增加一个元素‘test’,如下:
dic2[1].append('test') print(dic2) # {1: ['test'], 2: ['test'], 3: ['test']}
-
竟然把三个列表的值都给改了,这是为啥呢?先打印下他们的内存地址
print("dic2[1]:{}\ndic2[2]:{}\ndic2[3]:{}".format(id(dic2[1]),id(dic2[2]),id(dic2[3]))) # dic2[1]:1714986428808 # dic2[2]:1714986428808 # dic2[3]:1714986428808
-
原来它的所有键都指向了同一个内存地址,这也就不难怪修改其中一个而引发联动了,因为本质上只有一个列表。因此,在字典中定义不同的列表不要用fromkeys方法,还是老老实实定义吧
dic2 = {1: [], 2: [], 3: []} print(id(dic2[1])) # 1657985662344 print(id(dic2[2])) # 1657986500680 print(id(dic2[3])) # 1657986501960 dic2[1].append('test') print(dic2) # {1: ['test'], 2: [], 3: []}
-
使用循环来产生多key的字典:
dic2 = {} for k in range(10): dic2[k] = [] print(dic2) # {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}
- tips: fromkeys方法会返回一个新的字典,对原字典无影响
dic1 = {1:2} dic2 = dic1.fromkeys([1,2,3],'test') print(dic1) # {1: 2}