How can I mitigate the error in Python Dictionary?

How do I access to visibilities? I am trying like this: dev1['data']['results :visibilites ']

    dev1 = {
     "status": "OK",
     "data": {
     "results": [
       {
        "tradeRelCode": "ZT55",
        "customerCode": "ZC0",
        "customerName": "XYZ",
        "tier": "null1",
        "visibilites": [
          {
            "code": "ZS0004207",
            "name": "Aabc Systems Co.,Ltd",
            "siteVisibilityMap": {
            },
            "customerRef": "null1"
          }
        ]
      }
    ],
     "pageNumber": 3,
     "limit": 1,
     "total": 186
   }
 }

Upvotes: 0

Views: 55

Answers (3)

Valentin M.
Valentin M.

Reputation: 520

You can use dev1['data']['results'][0]['visibilites']. It will contain a list of one dictionary.

To access this dictionary directly, use dev1['data']['results'][0]['visibilites'][0]


dev['data'] represents a dictionary that has for key results.

You can access the item associated to results key (a list) using (dev1['data'])['results'].

To access the only member of this list, you use ((dev1['data'])['results'])[0]. This gives you a dictionary that has tradeRelCode, customerCode, customerName, tier and visibilites keys.

To access the item associated to visibilites key (a list), you have tu use (((dev1['data'])['results'])[0])['visibilites'].

To finally access the only dictionary contained in this list, you have tu use ((((dev1['data'])['results'])[0])['visibilites'])[0].

Parenthesis are here to show that python dig into each dictionary or list in order from left to right (python does not mind the parenthesis in the code, you can keep them if it is clearer for you.)

Upvotes: 2

Jatin Chauhan
Jatin Chauhan

Reputation: 325

Try this

dev1['data']['results'][0]['visibilites']

Reason:

This is a list -> dev1['data']['results']

So, access this -> dev1['data']['results'][0]

and then you obtain this ->

{'tradeRelCode': 'ZT55',
 'customerCode': 'ZC0',
 'customerName': 'XYZ',
 'tier': 'null1',
 'visibilites': [{'code': 'ZS0004207',
   'name': 'Aabc Systems Co.,Ltd',
   'siteVisibilityMap': {},
   'customerRef': 'null1'}]}

and then you can have -> dev1['data']['results'][0]['visibilites']

which results in ->

[{'code': 'ZS0004207',
  'name': 'Aabc Systems Co.,Ltd',
  'siteVisibilityMap': {},
  'customerRef': 'null1'}]

which is a list and you can index the first element which is another dictionary

Upvotes: 0

Yukht
Yukht

Reputation: 1

In your data structure use path

dev1['data']['results'][0]['visibilites']

Upvotes: 0

Related Questions