【发布时间】:2021-06-20 04:48:51
【问题描述】:
我的 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)
如果我删除周围的方括号,它将准确地打印正确的展平数据框。
有没有办法更新此代码,使其基本上可以进入该列表,然后开始展平字典?
【问题讨论】:
标签: python pandas dictionary flatten