1
\$\begingroup\$

I have a function general_statistics that takes a dict as input and get the wanted information. the function is working without any problem, but I want to know if I can do it with a pythonic way because I'm trying to improve my skills.

def general_statistics(input_data: dict):
        result = {}
        if 'general' in input_data.keys():
            if bool(input_data['general']):
                result['name'] = input_data['general']['name']
                result['information'] = input_data['general']['information']
                result['date'] = input_data['general']['creation_date']
                result['adress'] = input_data['general']['adress']
                if 'two' in input_data['general']['photo'].keys():
                    result['picture_person'] = input_data['general']['photo']['two']['ids']
                else:
                    result['picture_person'] = input_data['general']['photo']['one']['ids']
                if 'phones' in input_data['general'].keys():
                    result['phones'] = input_data['general']['phones']
                else:
                    pass
            else:
                result['name'] = ''
                result['information'] = ''
                result['date'] = ''
                result['adress'] = ''
        else:
            result['name'] = ''
            result['information'] = ''
            result['date'] = ''
            result['adress'] = ''
        if 'intrest' in input_data.keys():
            if bool(input_data['intrest']):
                intrest_list = []
                for gender in input_data['intrest']['gender_type']:
                    intrest_list.append(gender.split('/')[-1])
                    result['genders'] = intrest_list
        else:
            result['genders'] = []
        if 'command_details' in input_data.keys():
            if bool(input_data['command_details']):
                result['shiping'] = input_data['command_details']['shiping']
        else:
            result['shiping'] = ''
        if 'command_statistics' in input_data.keys():
            if bool(input_data['command_statistics']):
                result['com_statistics'] = input_data['command_statistics']
            else:
                command_statistics = {}
                command_statistics['count'] = ''
                command_statistics['items'] = ''
                command_statistics['payed'] = ''
                command_statistics['unpayed'] = ''
                result['com_statistics'] = command_statistics
        else:
            command_statistics = {}
            command_statistics['count'] = ''
            command_statistics['items'] = ''
            command_statistics['payed'] = ''
            command_statistics['unpayed'] = ''
            result['com_statistics'] = command_statistics

        result['com_statistics'] = input_data['command_statistics']
        if 'receiver_info' in input_data.keys():
            if bool(input_data['receiver_info']):
                if 'general' in input_data['receiver_info'].keys():
                    result['receiver_date'] = input_data['receiver_info']['general']['creation_date']
                    result['receiver_info'] = input_data['receiver_info']['general']['information']
                    if 'adress' in input_data['receiver_info']['general'].keys():
                        result['receiver_adress'] = input_data['receiver_info']['general']['adress']
                    else:
                        result['receiver_adress'] = ''
                    if 'two' in input_data['receiver_info']['general']['photo'].keys():
                        result['receiver_pictures'] = input_data['receiver_info']['general']['photo']['two']['ids']
                    else:
                        result['receiver_pictures'] = input_data['receiver_info']['general']['photo']['one']['ids']
                    result['receiver_stats'] = input_data['receiver_info']['command_statistics']
                    receiver_commands = []
                    if 'intrest' in input_data['receiver_info'].keys():
                        if input_data['receiver_info']['intrest']:
                            for gender in input_data['receiver_info']['intrest']['gender_type']:
                                receiver_commands.append(
                                    gender.split('/')[-1])
                                result['receiver_genders'] = receiver_commands
                    if 'receiver_photo' in input_data['receiver_info']['receiver_brand'].keys():
                        result['receiver_brand_id_photo'] = input_data[
                            'receiver_info']['receiver_brand']['receiver_photo']['id']
                    else:
                        result['receiver_brand_id_photo'] = ''
                else:
                    result['receiver_date'] = ''
                    result['receiver_adress'] = ''
                    result['receiver_stats'] = {}
                    result['receiver_pictures'] = ''
            else:
                result['receiver_date'] = ''
                result['receiver_adress'] = ''
                result['receiver_stats'] = {}
                result['receiver_pictures'] = ''
        else:
            result['receiver_date'] = ''
            result['receiver_adress'] = ''
            result['receiver_stats'] = {}
            result['receiver_pictures'] = ''
        return result

A small example of the input_data

input_data={
  "general": {
    "creation_date": "10/10/2015",
    "first_id": "10kahd",
    "name": "jacky",
    "information": "",
    "photo": {
      "one": {
        "ids": "1598",
      },
      "two": {
        "ids": "1489"
      },
      "tree": {
        "ids": "0298"
      }
    },
    "adress": "10,new york 159",
    "phones": [
      "number 1",
      "number 2"
    ],
    "cat": "01",
  },
  "command_details": {
    "shiping": "allowed",
  },
  "command_statistics": {
    "count": "226558",
    "items": "2015",
    "payed": "1500",
    "unpayed": "0"
  },
  "intrest": {
    "gender_type": [
      "chairs"
    ]
  },
  "cmd_id": "alsd952d",
  "receiver_info": {
    "general": {
      "name": "10,new york 159",
      "information": "",
      "creation_date": "01/06/2012",
      "photo": {
        "one": {
          "ids": "159z"
        },
        "two": {
          "ids": "98zzf"
        },
        "tree": {
          "ids": "pokAcs6"
        }
      },
    },
    "command_statistics": {
      "count": "15987643325",
      "all_cmd_count": "16549878466245",
      "all_cmd_count_years": 125,
      "sub_cmd": "1664987322"
    },
    "intrest": {
      "gender_ids": [
        "qsmplos"
      ],
      "gender_type": [
        "chairs",
        "pens"
      ]
    },
    "receiver_brand": {
      "brand_abdress": {
        "adress": "10,new york 159"
      }
    },
  }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How do I ask a good question?. \$\endgroup\$
    – BCdotWEB
    Commented Dec 1, 2021 at 7:23

1 Answer 1

1
\$\begingroup\$

Your

if 'general' in input_data.keys():
    if bool(input_data['general']):

could be

if 'general' in input_data:
    if input_data['general']:

or even

if general := input_data.get('general'):

and then use general instead of repeating input_data['general'].

Alternatively, instead of mostly repeated statements extracting the data, you could configure the extractions as data and then use some general extraction code. Something like this (only some of the entries):

def general_statistics(input_data: dict):
    def genders(data):
        return [gender.split('/')[-1] for gender in data]
    config = [
        ('name', ('general', 'name'), ''),
        ('information', ('general', 'information'), ''),
        ('date', ('general', 'creation_date'), ''),
        ('adress', ('general', 'adress'), ''),
        ('picture_person', ('general', 'photo', 'one', 'ids')),
        ('picture_person', ('general', 'photo', 'two', 'ids')),
        ('phones', ('general', 'phones')),
        ('genders', ('intrest', 'gender_type', genders), []),
    ]
    result = {}
    for key, path, *default in config:
        data = input_data
        for step in path:
            if isinstance(step, str):
                if step not in data:
                    if default:
                        result[key] = default[0]
                    break
                data = data[step]
            else:
                data = step(data)
        else:
            result[key] = data
    return result

You might also want to use a spell checker, as your data has quite a few typos ("intrest", "tree", "adress", "shiping", "payed", "unpayed").

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.