-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": [email protected],
    "creator": {
       "data": [
          {
              "name": "john" 
              "id": "123"
          },
          {
              "name": "victor"
              "id" : "345"
          }
        ]
  }
2
  • 2
    You should show what you tried and explain what "did not work" entails. Commented Aug 29, 2017 at 13:49
  • 1
    Would it not be dictionary["creator"]["data"]? Commented Aug 29, 2017 at 13:49

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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"

4 Comments

This worked for non-nested dictionaries, but not for a nested one !!
@user3447653: I have edited my answer. Does that make it clearer? If not, what exactly are you trying to achieve?
You may want to explain in greater detail what is going on here.
Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.