>>> def foo():
... d = {}
... list_1 = [1,2,3]
... list_2 = [4,5,6]
... list_3 = [7,8,9]
... for key1 in list_1:
... d[key1] = {}.fromkeys(list_2)
... for key2 in list_2:
... d[key1][key2] = {}.fromkeys(list_3)
... for key3 in list_3:
... d[key1][key2][key3] = 5
... return d
...
>>>
其中fromkeys的作用:
>>> {}.fromkeys(list_2)
{4: None, 5: None, 6: None}
>>> foo()
{1: {4: {8: 5, 9: 5, 7: 5}, 5: {8: 5, 9: 5, 7: 5}, 6: {8: 5, 9: 5, 7: 5}}, 2: {4: {8: 5, 9: 5, 7: 5}, 5: {8: 5, 9: 5, 7: 5}, 6: {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}}}
>>> list_1 = [1,2,3]
>>> list_2 = [4,5,6]
>>> list_3 = [7,8,9]
下边是简写方式:
>>> {k1:{k2:{k3:5 for k3 in list_3} for k2 in list_2} for k1 in list_1}
{1: {4: {8: 5, 9: 5, 7: 5}, 5: {8: 5, 9: 5, 7: 5}, 6: {8: 5, 9: 5, 7: 5}}, 2: {4: {8: 5, 9: 5, 7: 5}, 5: {8: 5, 9: 5, 7: 5}, 6: {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群