gpt4 book ai didi

python - 在 python 中映射嵌套字典

转载 作者:行者123 更新时间:2023-11-30 23:24:08 27 4
gpt4 key购买 nike

我正在转换 XML 文档中的字段,以便可以加载到普通的关系数据库中。我已将 XML 文档转换为一堆嵌套字典。我希望提取的一些值位于嵌套字典中,因此我需要先将其展平。

很简单,但我想创建一个映射,让我可以预先指定要提取的内容。

示例

input_dict = {
'authors': [{'name': u'Google, Inc.'}],
'islink': False,
}

mapping = ['islink',<???>]

期望的输出

In: tuple(input_dict[key] for key in mapping)
Out: (False, 'Google, Inc.')

这显然行不通:

In: [input_dict[key] for key in ['islink',['authors'][0]['name']]]
Out: TypeError: string indices must be integers, not str

最佳答案

还有:

from collections import Iterable

def flatten(x):
result = []
if isinstance(x, dict):
x = x.values()
for el in x:
if isinstance(el, Iterable) and not isinstance(el, str):
result.extend(flatten(el))
else:
result.append(el)
return result

这一次是 python3 友好的;-)

>>> dd = {'a': 42, 'c': 12, 'b': [{1: 2, 2: 3, 3: 4}]}
>>> flatten(dd)
[42, 12, 2, 3, 4]

这是一个支持 key 过滤的版本:

def flatten(x, keys=None):
result = []
if isinstance(x, dict):
if keys is None:
x = x.values()
else:
x = dict(filter(lambda t: t[0] in keys, x.items())).values()
for el in x:
if isinstance(el, Iterable) and not isinstance(el, str):
result.extend(flatten(el, keys))
else:
result.append(el)
return result

结果:

>>> flatten(dd, keys=['a'])
[42]
>>> flatten(dd, keys=['a','b']) # even though 'b' is selected, no sub key has been
[42]
>>> flatten(dd, keys=['a','b',1]) # to get a subkey, 'b' needs to be selected
[42, 2]
>>> flatten(dd,keys=['a',1]) # if you don't then there's no subkey selected
[42]
>>> flatten(dd, keys=['a','b',2,3])
[42, 3, 4]

对于您的用例:

>>> input_dict = {'authors': [{'name': 'Google, Inc.'}],'islink': False,}
>>> flatten(input_dict)
[False, 'Google, Inc.']

注意:我改编自 that answer about list flattening 的答案

关于python - 在 python 中映射嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23619568/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com