# 使用 yield 压平多层嵌套字典列表混合数据

```nest_dict = {
'a': 1,
'b': {
'c': 2,
'd': 3,
'e': {'f': 4}
},
'g': {'h': 5},
'i': 6,
'j': {'k': {'l': {'m': 8}}},
'n': [1, {'o': 1, 'p': [1, 2, 3],  'q': {'r': {'s': 100}}}, 3, [1, 2, 3], 5]
}```

```{'a': 1,
'b_c': 2,
'b_d': 3,
'b_e_f': 4,
'g_h': 5,
'i': 6,
'j_k_l_m': 8,
'n_0': 1,
'n_1_o': 1,
'n_1_p_0': 1,
'n_1_p_1': 2,
'n_1_p_2': 3,
'n_1_q_r_s': 100,
'n_2': 3,
'n_3_0': 1,
'n_3_1': 2,
'n_3_2': 3,
'n_4': 5}```

```def flat(x):
for key, value in x.items():
if isinstance(value, dict):
for k, v in flat(value):
k = f'{key}_{k}'
yield (k, v)
else:
yield (key, value)```

```def flat(x):
for key, value in x.items():
if isinstance(value, dict):
for k, v in flat(value):
k = f'{key}_{k}'
yield (k, v)
elif isinstance(value, list):
"一大堆处理列表的代码"
else:
yield (key, value)```

```def iter_x(x):
if isinstance(x, dict):
for key, value in x.items():
yield (key, value)
elif isinstance(x, list):
for index, value in enumerate(x):
yield (index, value)```

```def flat(x):
for key, value in iter_x(x):
if isinstance(value, (dict, list)):
for k, v in flat(value):
k = f'{key}_{k}'
yield (k, v)
else:
yield (key, value)```

282 篇文章41 人订阅

0 条评论