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[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
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: []}
dic2 = {}
for k in range(10):
dic2[k] = []
print(dic2) # {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}
dic1 = {1:2}
dic2 = dic1.fromkeys([1,2,3],‘test‘)
print(dic1) # {1: 2}
print(dic2) # {1: ‘test‘, 2: ‘test‘, 3: ‘test‘}
原文地址:https://blog.51cto.com/hld1992/2366257
时间: 2024-10-09 11:33:03