-2

I am trying to access the value of creator from the below dictionary along with other values like description and email.

I tried converting it to json and then access the keys. But it did not work. Is the only way to iterate the entire dictionary and get the values of all keys.

Any suggestions would be great !!

  {
    "description": xxx,
    "email": xxx@scotiabank.com,
    "creator": {
       "data": [
          {
              "name": "john" 
              "id": "123"
          },
          {
              "name": "victor"
              "id" : "345"
          }
        ]
  }
user3447653
  • 3,968
  • 12
  • 58
  • 100

2 Answers2

1

dict["description"] will return 'xxx'

dict["creator"]['data'] will return [{"name": "john","id": "123"},{"name": "victor","id" : "345"}]

dict["creator"]['data'][1]["name"] will return "john"

Where dict is your dictionary

0

Suppose you have a dictionary of any depth.

dict = {"description": xxx, ...

You can get items from the dictionary by specifying the key:

desc = dict["description"] # returns "xxx"

You can do this recursively:

name = dict["creator"]["data"] # returns list of people [{"name": "john", "id": "123"}, {"name": "victor", "id": "345"}]
name = dict["creator"]["data"][0] # returns the first item in the list {"name": "john", "id": "123"}
name = dict["creator"]["data"][0]["name"] # returns "john"
Honza Zíka
  • 495
  • 3
  • 12
  • This worked for non-nested dictionaries, but not for a nested one !! – user3447653 Aug 29 '17 at 13:51
  • @user3447653: I have edited my answer. Does that make it clearer? If not, what exactly are you trying to achieve? – Honza Zíka Aug 29 '17 at 13:55
  • You may want to explain in greater detail what is going on here. – Gassa Aug 29 '17 at 14:31
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Aug 29 '17 at 15:46