简体   繁体   English

如何从嵌套字典中动态提取键和值?

[英]How to dynamically extract key and value from nested dictionary?

I am struggling with how to dynamically extract values from a dictionary record and I am hoping if someone can help. 我正在努力从字典记录中动态提取值,我希望有人能提供帮助。

Here's what my dictionary record looks like from a system API. 这是我的字典记录从系统API看起来的样子。

from collections import OrderedDict

OrderedDict([('Id', '0061J00000QPnGoQAL'),
             ('Name', 'Acme X-Author RenewalSep tx'),
             ('Account',
              OrderedDict([('Region__c', 'Americas'), ('Name', 'Accenture')])),
             ('CreatedBy', OrderedDict([('Name', 'Jerret Moz')]))])

And my goal here is to make the dictionary record looks like 我的目标是使字典记录看起来像

OrderedDict([('Id', '0061J00000QPnGoQAL'),
             ('Name', 'Acme X-Author'),
             ('Region__c', 'Americas'), 
             ('Name', 'Accenture'),
             ('Name', 'Jerret Moz')])

If even more ideally but not sure if possible 如果更理想,但不确定是否可能

 OrderedDict([('Id', '0061J00000QPnGoQAL'),
              ('Name', 'Acme X-Author'),
              ('Account.Region__c', 'Americas'), 
              ('Account.Name', 'Accenture'),
              ('CreatedBy.Name', 'Jerret Moz')])

Any help or advice is appreciated! 任何帮助或建议,不胜感激! Thanks. 谢谢。

You're question is fairly unclear. 您的问题还不清楚。 Especially when it comes to what input you're going to have. 特别是涉及到您将要输入的内容时。 Thus the answer below works for the input you provided, but you will probably need to adapt the conditons, splits, and others aspects to your needs. 因此,以下答案适用于您提供的输入,但是您可能需要根据您的需要调整条件,分割和其他方面。

Your input: 您的输入:

from collections import OrderedDict

D = OrderedDict([('Id', '0061J00000QPnGoQAL'),
             ('Name', 'Acme X-Author RenewalSep tx'),
             ('Account',
              OrderedDict([('Region__c', 'Americas'), ('Name', 'Accenture')])),
             ('CreatedBy', OrderedDict([('Name', 'Jerret Moz')]))])

How to get the second desired output: 如何获得第二个所需的输出:

D2 = OrderedDict()

for key, value in D.items():
    if key.lower() == "id":
        D2[key] = value
    elif key.lower() == "name":
        D2[key] = value.split(" RenewalSep tx")[0]
    elif type(value) == OrderedDict:
        for key2, value2 in value.items():
            D2[key + "." +  key2] = value2

Output: 输出:

OrderedDict([('Id', '0061J00000QPnGoQAL'),
         ('Name', 'Acme X-Author'),
         ('Account.Region__c', 'Americas'),
         ('Account.Name', 'Accenture'),
         ('CreatedBy.Name', 'Jerret Moz')])

Go through the dict, test if the value is a dict, if it is go inside and append. 通过dict,测试该值是否为dict,如果在内部并追加。

temp = OrderedDict()

for key,value in dict_name:
    if isinstance(value,dict):
        temp.update(value)

dict_name.update(temp)

You unpack the dictionaries inside into a new OrderedDict and add it to the original OrderedDict 您将其中的字典解压缩到新的OrderedDict中,并将其添加到原始OrderedDict中

def get_dotted_dict(d, old=""):
    new = OrderedDict()
    for k,v in d.items():
        if isinstance(v, dict):
            for k2, v2 in v.items():
                nk = '.'.join(filter(bool, [old,k,k2]))
                new[nk] = get_dotted_form(v2, nk) if isinstance(v2, dict) else v2
        else:   
            new[k] = v

    return new

d = OrderedDict([('Id', '0061J00000QPnGoQAL'), ('Name', 'Acme X-Author RenewalSep tx'), ('Account', OrderedDict([('Region__c', 'Americas'), ('Name', 'Accenture')])), ('CreatedBy', OrderedDict([('Name', 'Jerret Moz')]))])
nd = get_dotted_form(d)
print nd
# OrderedDict([('Id', '0061J00000QPnGoQAL'), ('Name', 'Acme X-Author RenewalSep tx'), ('Account.Region__c', 'Americas'), ('Account.Name', 'Accenture'), ('CreatedBy.Name', 'Jerret Moz')])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从嵌套字典中提取键值对并在json中输出 - How to extract a key value pair from a nested dictionary and output it in json 如何从python中的嵌套字典中提取特定键的值并返回值列表 - How to extract a specific key's value from a nested dictionary in python and return a list of the values 我不知道如何从嵌套字典中提取特定的键:值对 - I can't figure out how to extract specific key:value pairs from a nested dictionary 如何从python嵌套列表中的嵌套字典中提取值 - How to extract the value from a nested dictionary within a nested list in python 如何从嵌套字典中按值获取字典键? - How to get a dictionary key by value from a nested dictionary? "从嵌套字典中按键提取值" - Extract values by key from a nested dictionary 如何从嵌套的 for 循环中提取更新的字典值? - How to extract updated dictionary value from nested for loop? 如何从 txt 文件中读取值是嵌套字典并且嵌套字典的键由我给出的字典? - How to read from a txt file into a dictionary where the value is a nested dictionary and the key of the nested dictionary is given by me? 如何根据 python 中的键值从字典中提取 - How to extract from a dictionary based on a key value in python pandas中如何从深度字典中提取键值 || Python || dataframe - How to extract key value from deep dictionary in pandas || Python || dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM