好,所以我有一个嵌套字典的列表,类似:
[{''摘要':'details1','web_url':'www.google.com','多媒体':[{'等级':'0','子类型':'xlarge','标题' :无,“旧版”:{'xlargewidth':600,'xlargeheight':400}},{{'rank':1,'subtype':'xlarge','caption':无,'legacy':{' xlargewidth':600,'xlargeheight':400}]}},{{'Abstract':'details2','web_url':'www.facebook.com','multimedia':[{'rank':0,'subtype ':'xlarge','caption':无,'legacy':{'xlargewidth':600,'xlargeheight':400}},{{'rank':1,'subtype':'xlarge','caption' :无,“旧版”:{'xlargewidth':600,'xlargeheight':400}]}}]
我想将其转换为平面词典列表
[{''摘要':'details1','web_url':'www.google.com','multimedia.rank':'0','multimedia.subtype':'xlarge','multimedia.caption' :none,'multimedia.legacy.xlargewidth':600 ....},{'Abstract':'details1','web_url':'www.facebook.com','multimedia.rank':'0',' multimedia.subtype':'xlarge','multimedia.caption':None,'multimedia.legacy.xlargewidth':600 ....}]
我编写了以下代码,但它创建了一个大的扁平字典。
def flatten_dictionary(input_dict, separator='.', prefix=''):
flat_dictionary = {}
for key, value in input_dict.items(): ##iterating through all the items in the input dictionary
if isinstance(value, dict) and value: ##checking if each item is a dictionary or not
deeper = flatten_dictionary(value, separator, prefix+key+separator) ##recursively checking each item of the nested dictionary within dictionary
flat_dictionary.update({key2: val2 for key2, val2 in deeper.items()})
#print(deeper)
elif isinstance(value, list) and value:
for index, sublist in enumerate(value, start=1):
if isinstance(sublist, dict) and sublist:
deeper = flatten_dictionary(sublist, separator, prefix+key+separator+str(index)+separator)
flat_dictionary.update({key2: val2 for key2, val2 in deeper.items()})
else:
flat_dictionary[prefix+key+separator+str(index)] = value
else:
flat_dictionary[prefix+key] = value
return flat_dictionary