【工程类】【Python】字典嵌套赋值

在一些时候,我们经常需要对字典进行嵌套赋值,但是每次取出来还要判断是否存在,所以我们希望有一种方法能够方便的对字典进行初始化。。以下是字典嵌套初始化的方法。

def pack_data():
	dic = {}
	list1=[1,2,3]
	list2=[4,5,6]
	list3=[7,8,9]
	for layer1 in list1:
		dic[layer1] = {}.fromkeys(list2)
		for layer2 in list2:
			dic[layer1][layer2] = {}.fromkeys(list3)
			for layer3 in list3:
				dic[layer1][layer2][layer3]=5
	return dic
'''
得到的结果是:
{1: {4: {8: 5, 9: 5, 7: 5}, 
     5: {8: 5, 9: 5, 7: 5}, 
2:  {4: {8: 5, 9: 5, 7: 5}, 
     5: {8: 5, 9: 5, 7: 5}, 
3:  {4: {8: 5, 9: 5, 7: 5}, 
     5: {8: 5, 9: 5, 7: 5}, 
     6: {8: 5, 9: 5, 7: 5}}}
'''

你可能感兴趣的:(Python)