我有我的 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)
如果我删除周围的方括号,它将准确打印正确的扁平数据框。
有没有办法更新此代码,使其基本上可以进入该列表,然后开始扁平化字典?
答案 0 :(得分:1)
您可以在函数的开头添加代码来循环遍历列表。以下代码适用于您提到的场景。
items = []
if isinstance(dictionary, list):
for listval in dictionary:
items.extend(flatten(listval).items())
else:
for key, value in dictionary.items():