Python 使用dict复制嵌套的for循环

Python 使用dict复制嵌套的for循环,python,dictionary,Python,Dictionary,给定以下代码: 列表列表的最小示例: c=['dog','Sg','Good'],['cat','Pl','ok'],['dog','Pl','Bad'], ['dog'、'Sg'、'Good']、['cat'、'Pl'、'ok']、['dog'、'Pl'、'ok'], ['dog'、'Sg'、'Good']、['cat'、'Sg'、'Good']、['dog'、'Pl'、'Bad'], ['dog'、'Sg'、'Good']、['cat'、'Pl'、'ok']、['dog'、'Pl'、'Bad

给定以下代码:

列表列表的最小示例:
c=['dog','Sg','Good'],['cat','Pl','ok'],['dog','Pl','Bad'],
['dog'、'Sg'、'Good']、['cat'、'Pl'、'ok']、['dog'、'Pl'、'ok'],
['dog'、'Sg'、'Good']、['cat'、'Sg'、'Good']、['dog'、'Pl'、'Bad'],
['dog'、'Sg'、'Good']、['cat'、'Pl'、'ok']、['dog'、'Pl'、'Bad']]
c
outer_keys=set()
内部按键=设置()
对于c中的x:
外部_键。添加(x[0])
内部|键|=集合(x[1:])
使用
for循环创建
dict
引理=dict() 对于外部_键中的i: j_d=dict() 对于内螺纹键中的j: j_d[j]=0 j_d[i]=0#这是我无法用理解力复制的线 引理[i]=j_d
循环的
结果:
{'dog':{'ok':0,'Pl':0,'Good':0,'Bad':0,'Sg':0,'dog':0},
'cat':{'Okay':0,'Pl':0,'Good':0,'Bad':0,'Sg':0,'cat':0}
使用:
  • 这就是我需要帮助的地方。我无法用
    dict
    理解复制
    for循环
Lemma={j:{i:0表示内部_键中的i}表示外部_键中的j}
注意:
dog
应位于外部
dog
值内,对于
cat

我的
听写理解
结果:
{'dog':{'Okay':0,'Pl':0,'Good':0,'Bad':0,'Sg':0},
'cat':{'Okay':0'Pl':0'Good':0'Bad':0'Sg':0}
问题:
  • 如何使用
    dict comprehension
    复制
    for循环的结果
  • 秩序不重要

您可以将
dict.fromkeys
内键{j}
一起使用:

>>> {j: dict.fromkeys(inner_keys | {j}, 0) for j in outer_keys}
{'cat': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Pl': 0, 'Sg': 0, 'cat': 0},
 'dog': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Pl': 0, 'Sg': 0, 'dog': 0}}

只需从您的内部dict创建一个新的
dict

>>> {j: dict({i: 0 for i in inner_keys}, **{j:0}) for j in outer_keys}
{'dog': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Sg': 0, 'dog': 0, 'Pl': 0}, 'cat': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Sg': 0, 'Pl': 0, 'cat': 0}}