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"]
}
]
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']
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']
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.