0

In JSON data file, I'd like to obtain the first elements in the object list. So, John, Sam, and James in this case.

I can get first element like this below, but how do I loop through the first objects in that list without specifically replacing below values like 0,1,2?

data[0]["name"][0]
data[1]["name"][0]
data[2]["name"][0]
data[3]["name"][0]
...

code

with open('data.json') as f:
    data = json.load(f)
##prints list
print data[0]["name"]
##print first element in that list
print data[0]["name"][0]

json

[{
       "name":[ "John", "Sam", "Rick"]
   },
   {
       "name":[ "Sam", "Paul", "Like"]
   },
{
       "name":[ "James", "Saul", "Jack"]
   }
]
1
  • 1
    What did you try so far? If you have not googled "for loop in python" so far, I strongly recommend you to do so. Commented Apr 1, 2019 at 17:43

3 Answers 3

3
def get_first_name_from_each_dict(data_list):
    return [d['name'][0] for d in data]
print(get_first_name_from_each_dict([
    {
        "name": ["John", "Sam", "Rick"]
    },
    {
        "name": ["Sam", "Paul", "Like"]
    },
    {
        "name": ["James", "Saul", "Jack"]
    }
]))
['John', 'Sam', 'James']
Sign up to request clarification or add additional context in comments.

1 Comment

By the way, if you wish to obtain unique names that appear first in each list, change the output list to a set.
1

You should look into the types of loops in Python to fully understand what this code is doing

You can use a for loop to iterate through every object in the data list

names = []
for name_list in data:
    names.append(name_list["name"][0])

Or you can do it all in one line with list comprehension

names = [name_list["name"][0] for name_list in data]

Comments

1
names_res = map(lambda i: i['name'][0], data)

It outputs a lazy 'generator' which is memory efficient, which is much better than consuming all data

print(list(names_res))

>> ['John', 'Sam', 'James']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.