john doe
john doe

Reputation: 2253

Problems while parsing a nested json/list in python3?

I have a very large list alist which has a dict and a nested list like this:

a_list = [{'A': [], 's': {'code': '0', 'credits': '0', 'msg': 'OK'}},
 {'A': [{'dictionary': 'True',
    'item': 'pineapples',
    'id': '13',
    'score': '9.7899',
    'rollup': {'True': 'OK', 'Fiz': 'Yes'},
    'variant_list': [{'endp': '8', 'form': 'pineapple', 'register': '0'}]}], 'status': {'codecheck': '0', 'cred': '90809890', 'msg': 'OK'}},
......

{'A': [], 's': {'code': '0', 'credits': '0', 'msg': 'OK'}},
    ]

How can I extract the extract the item parameter if and only if exist into a list like this:

['NaN', 'pineapples', 'NaN']

I do not understand how to parse it since it has a very nested structure, the main issue which I am struggling with is to accessing to each element of the list and then to the other list and leaving a NaN string.

Upvotes: 1

Views: 298

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use the following approach(list comprehension):

a_list = [{'A': [], 's': {'code': '0', 'credits': '0', 'msg': 'OK'}},
          {'A': [{'dictionary': 'True',
                  'item': 'pineapples',
                  'id': '13',
                  'score': '9.7899',
                  'rollup': {'True': 'OK', 'Fiz': 'Yes'},
                  'variant_list': [{'endp': '8', 'form': 'pineapple', 'register': '0'}]}],
           'status': {'codecheck': '0', 'cred': '90809890', 'msg': 'OK'}},
          {'A': [], 's': {'code': '0', 'credits': '0', 'msg': 'OK'}},
          ]

result = ['NaN' if not len(o['A']) else o['A'][0]['item'] for o in a_list]
print(result)

The output:

['NaN', 'pineapples', 'NaN']

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

a certain condition, in your case, is 'NaN' if not len(o['A']) else o['A'][0]['item']

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Upvotes: 1

Related Questions