skip to Main Content

I understand this question may have been asked in many different formats in the past. I also checked the recommended answers when I wrote the question title, and I haven’t found what I need.

I’m new to Python so my understanding of lists and dictionaries is slowly growing. I’m struggling at the moment with what I can only describe as a nested dictionary, but I don’t think that’s the right way to refer to it.

Using requests.get(…).json() I obtain a list of a json-like object, like this:

[{‘key’: {‘key’: ‘projkey1’}, ‘name’: ‘projname1’}, {‘key’: {‘key’:
‘projkey2’}, ‘name’: ‘projname2’}, {‘key’: {‘key’: ‘projkey3’},
‘name’: ‘projname3’}]

Let’s assume that’s stored in ‘ppl’. I now use the following code:

for entries in ppl:
    print(entries)

And that returns the following:

{‘key’: {‘key’: ‘projkey1’}, ‘name’: ‘projname1’}

{‘key’: {‘key’: ‘projkey2’}, ‘name’: ‘projname2’}

{‘key’: {‘key’: ‘projkey3’}, ‘name’: ‘projname3’}

Next, if I want to get the name element, I can simply ask for:

print(entries.get('name'))

And that’ll return just the entry of projname1, projname2, etc.

Here’s my problem. If I ask for print(entries.get(‘key’)), I actually get back:

{‘key’: ‘projkey1’}

It’s obvious why – it’s because "key" is also nested under "key", but I don’t know how to get just the item under that nested "key".

EDIT: I have the answer, but now, why is my data being returned with each character on a new line?

Using this code:

for entries in ppl:
    print(entries.get('key')['key'])
    for keys in entries.get('key')['key']:
        print(keys)

The first print statement returns:

projkey1

The second returns:

  • p
  • r
  • o
  • j
  • k
  • e
  • y
  • 1

Why is my data being output as individual characters?

2

Answers


  1. Use entries["key"]["key"]

    This will first access {'key':'projkey1'}, and then get just 'projkey1'.

    Login or Signup to reply.
  2. Answer for the edit:

    You are looping through each character individually, and then printing each one. This means they are printed on different lines.

    You should instead add each character to a string and print that:

    for entries in ppl:
    
        result = ""
    
        print(entries.get('key')['key'])
    
        for char in entries.get('key')['key']:
            result += char
    
        print(result)
    

    I changed the name of the iteration variable from keys to char because it accesses one character at a time rather than all the keys.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search