flatten函数适用于dictionary,但不适用于包含dictionary的列表



我有我的python脚本,它在展开字典时非常有效,但是,当它是字典列表时,由于列表没有方法-items(),它将无法工作。

def flatten(dictionary, p_key=None, parent_key=False, separator='.'):
items = []
for key, value in dictionary.items():
if parent_key:
new_key = f"{str(p_key)}{separator}{key}"
else:
new_key = p_key if p_key else key
if isinstance(value, mm):
items.extend(flatten(
dictionary=value,
p_key=new_key,
parent_key=True,
separator=separator).items())
elif isinstance(value, list):
for k, v in enumerate(value):
items.extend(flatten(
dictionary={str(k): v},
p_key=new_key,
parent_key=False,
separator=separator).items())
else:
items.append((new_key, value))
return dict(items)

d = [{ 
"_id" : 1, 
"labelId" : [
6422
], 
"levels" : [
{
"active" : "true", 
"level" : 3, 
"actions" : [
{
"isActive" : "true"
}]
}]
}]

x = flatten(d)
x = json_normalize(x)
print(x)

如果我去掉周围的方括号,它将准确地打印出正确的扁平数据帧。

有没有办法更新这个代码,让它基本上可以进入列表,然后开始扁平化字典?

您可以在函数开头添加代码以循环遍历列表。下面的代码适用于您提到的场景。

items = []
if isinstance(dictionary, list):
for listval in dictionary:
items.extend(flatten(listval).items())
else:    
for key, value in dictionary.items():

最新更新