這個問題與Flatten nested dictionaries, compressing keys有關。我使用了這個想法并修改為未嵌套的字典串列,但無法做到。
我的輸入將是一個字典,它可以具有嵌套字典或嵌套串列(字典串列),如函式 flatten_dict_list 的輸入所示
下面是我的源代碼:
def flatten_dict_list(d, parent_key='', sep='.'):
items = []
for k, v in d.items():
print("***")
new_key = parent_key sep k if parent_key else k
print(new_key)
if isinstance(v, list):
for z in v:
if isinstance(z, collections.abc.MutableMapping):
print(type(z))
print(z)
items.extend(flatten_dict_list(z, new_key, sep=sep).items())
else:
print(type(z))
print(z)
items.append((new_key, z))
else:
if isinstance(v, collections.abc.MutableMapping):
print(type(v))
print(v)
items.extend(flatten_dict_list(v, new_key, sep=sep).items())
else:
print(type(v))
print(v)
items.append((new_key, v))
return dict(items)
print(flatten_dict_list({'a': 1, 'c': [{'a': 2, 'b': {'x': 5, 'y' : 10}}, {'test': 9999}, [{'s': 2}, {'t': 100}]], 'd': [1, 2, 3]}))
預期輸出為:{'a': 1, 'c.a': 2, 'cbx': 5, 'cby': 10, 'c.test': 9999, 'c.s': 2, 'c. t':100,'d':3}
我的實際結果是: {'a': 1, 'c.a': 2, 'cbx': 5, 'cby': 10, 'c.test': 9999, 'c': [{'s': 2},{'t':100}],'d':3}
uj5u.com熱心網友回復:
鑒于:
- 你不關心兩者
{'a': {'b': 1, 'c': 2}}并且{'a': [{'b': 1}, {'c': 2}]}會映射到相同的{'a.b': 1, 'a.c': 2} - 輸入資料結構中的串列中除了字典之外不會有任何其他內容
這似乎是一個相當干凈的解決方案:
def _compound_key_value(xs, prefix):
if isinstance(xs, list):
for x in xs:
yield from _compound_key_value(x, prefix)
elif isinstance(xs, dict):
for k, v in xs.items():
for p, r in _compound_key_value(v, prefix):
yield prefix (k,) p, r
else:
yield prefix, xs
def flatten_dict_list(dl):
return {'.'.join(k): v for k, v in _compound_key_value(dl, ())}
print(flatten_dict_list({'a': 1, 'c': [{'a': 2, 'b': {'x': 5, 'y' : 10}}, {'test': 9999}, [{'s': 2}, {'t': 100}]], 'd': [1, 2, 3]}))
輸出
{'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'c.test': 9999, 'c.s': 2, 'c.t': 100, 'd': 3}
請注意,它是遞回的,就像您開始使用的解決方案一樣,所以我還假設最大遞回深度不會成為問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418712.html
標籤:
