[Python] How to reduce the nested block dictionary in python

Discussão em 'Python' iniciado por Stack, Junho 23, 2025.

  1. Stack

    Stack Membro Participativo

    I have sample dictionary is below

    How to reduce the Loop because Its more than 5 blocks and pylint its failing

    Below are the conditions need to checked


    • Checking whether People Key exists


    • if 'People' exist then looping


    • checking whether 'role_id' exists in People


    • return base dictionary id if role_id is None


    • checking Role is available in event dictionary


    • if Role not available then pass base Developer


    • if Role key present then take roleName from the Role


    • If 'Tester' == roleName available then create a new dictionary

      event = {
      "id": "100",
      "Dept": "Developer",
      "Role": [{
      "id": "201",
      "roleName": "UI"
      },
      {
      "id": "202",
      "roleName": "Tester"
      }
      ],
      "People": [{
      "id": "290",
      "fullName": "Jo",
      "email": "jo@test.com",
      "role_id": [{
      "S": "201"
      },
      {
      "S": "202"
      }
      ]
      }]


      }

    Code is below which is working

    def get_dict(event):
    total_list = ['Tester','Developer']
    Developer = {'id':None}
    if 'People' in event: #Checking whether People Key exists
    for people in event['People']: # if 'People' exist then looping
    if people['role_id'] is None: #checking whether 'role_id' exists
    return Developer #return base dictionary id role_id None
    for role_id in people['role_id']: #if not None
    if 'Role' not in event: #checking ROle is available in event dictionary
    return Developer #if not then pass base Developer
    for role in event['Role']: #if Role key present
    if role['id'] == role_id['S']:
    role_name = role['roleName']
    if role_name in total_list:
    if "Tester" == role_name:
    Developer = {'id': event['People'][0]['id'],
    'role':role_name}
    return Developer
    get_dict(event)


    My output and Expected

    {'id': '290', 'role': 'Tester'}


    My Problem I am facing. How to reduce the Loop because Its more than 5 blocks and pylint its failing?

    p.s. Yes, it is my coding intention to exit immediately if the first people doesn't have a role_id.

    Continue reading...

Compartilhe esta Página