简体   繁体   English

如何从嵌套字典中提取元素

[英]How to extract elements from nested dict

1.I need to get the value for business' name and append it to a list. 1.我需要将企业名称和 append 的值添加到列表中。

2.I need to get the value policies and append to a list after checking parent. 2.我需要在检查父母后将价值政策和 append 放到一个列表中。

3.if parent is Marketing name has to added to level1. 3.如果父母是营销名称必须添加到level1。

4.if parent is Advertising name has to added to level2. 4.如果父母是广告名称必须添加到level2。

5.if some place Business is [] I need to pass None instead of Null List 5.如果某个地方的业务是 [] 我需要通过 None 而不是 Null 列表

  1. Also need to check key exists or not for some keys there is a chance of missing policies, business还需要检查密钥是否存在某些密钥有可能丢失策略,业务

Sample dictionary is below样本字典如下

searchtest = [{'_index': 'newtest',
  '_type': '_doc',
  '_id': '100',
  '_score': 1.0,
  '_source': {'id': '100',
   'name': 'A',
   'Business': [{'id': '7', 'name': 'Enterprise'},
    {'id': '8', 'name': 'Customer'}],
   'policies': [{'id': '332',
     'name': 'Second division',
     'parent': 'Marketing'},
    {'id': '3323', 'name': 'First division', 'parent': 'Marketing'}]}},
 {'_index': 'newtest',
  '_type': '_doc',
  '_id': '101',
  '_score': 1.0,
  '_source': {'id': '101',
   'name': 'B',
   'Business': [{'id': '7'},
    {'id': '8', 'name': 'Customer'}],
   'policies': [{'id': '332',
     'name': 'Second division',
     'parent': 'Marketing'},
    {'id': '3323', 'name': 'First division', 'parent': 'Marketing'}]}}]

Expected out预计出局

[
  {
    "id": "100",
    "name": "A",
    "Business": ["Enterprise", "Customer"],
    "level1": ['Second division', 'First division'],
    "level2": [ ]
  },
  {
    "id": "101",
    "name": "B",
    "Business": ["Enterprise", "Customer"],
    "level1": ['Second division', 'First division'],
    "level2": [ ]
  }
]

COde is below代码如下

def do_the_thing(lst):
    resp = []

    parents_mapper = {
        'Marketing': 'level1',
        'Advertising': 'level2'
    }

    for el in lst:
        d = {
            'id': el['_source']['id'],
            'name': el['_source']['name'],
            'Business': [],
            'level1': [],
            'level2': []
        }
        for business in el.get("_source", {}).get("business", {}).get("name", ""):
            business_name = business.get('name')
            if business_name:
                d['Business'].append(business_name)

        for policy in el.get('policies', []):
            policy_parent = policy.get('parent')
            parent_found = parents_mapper.get(policy_parent)
            policy_name = policy.get('name')
            if parent_found and policy_name:
                d[parent_found].append(policy_name)

        resp.append(d)
    return resp


if __name__ == "__main__":
    import pprint
    pp = pprint.PrettyPrinter(4)
    pp.pprint(do_the_thing(searchtest))

My output我的 output

[   {'Business': [], 'id': '100', 'level1': [], 'level2': [], 'name': 'A'},
    {'Business': [], 'id': '101', 'level1': [], 'level2': [], 'name': 'B'}]

The problem in my output you can see: 'Business', 'level1' is [] is null list.我的 output 中的问题你可以看到:'Business', 'level1' is [] is null list。

Adding one more dictionary for testing再添加一本字典进行测试

searchtest = [{'_index': 'newtest',
  '_type': '_doc',
  '_id': '100',
  '_score': 1.0,
  '_source': {'id': '100',
   'name': 'A',
   'policies': [{'id': '332',
     'name': 'Second division',
     'parent': 'Marketing'},
    {'id': '3323', 'name': 'First division', 'parent': 'Marketing'}]}},
 {'_index': 'newtest',
  '_type': '_doc',
  '_id': '101',
  '_score': 1.0,
  '_source': {'id': '101',
   'name': 'B',
   'Business': [{'id': '9'}, {'id': '10', 'name': 'Customer'}],
   'policies': [{'id': '332',
     'name': 'Second division',
     'parent': 'Marketing'},
    {'id': '3323', 'name': 'First division', 'parent': 'Advertising'}]}}]
  • In the above dictionary you can see that there is no Business in 100 key and for 101 there is no name inside the Business key.在上面的字典中,您可以看到 100 键中没有业务,而对于 101,业务键中没有名称。 So there will be key error will be coming.所以会出现关键错误。 Need to handle that需要处理

You are not collecting data from dict, You have to select particular key to get it's value.您不是从 dict 收集数据,您必须 select 特定键才能获得它的价值。

replace this:替换这个:

for el in lst:
        d = {
            'id': el['_source']['id'],
            'name': el['_source']['name'],
            'Business': [],
            'level1': [],
            'level2': []
        }

with this:有了这个:

for el in data:
        d = {
            'id'       : el['_source']['id'],
            'name'     : el['_source']['name'],
            'Business' : [name['name'] for name in el['_source']['Business']],
            'level1'    : [name['name'] for name in el['_source']['policies']],
            'level2'   : []
        }

output: output:

[   {   'Business': ['Enterprise', 'Customer'],
        'id': '100',
        'level1': ['Second division', 'First division'],
        'level2': [],
        'name': 'A'},
    {   'Business': ['Enterprise', 'Customer'],
        'id': '101',
        'level1': ['Second division', 'First division'],
        'level2': [],
        'name': 'B'}]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM