Home > Software engineering >  python list of dictionary get values
python list of dictionary get values

Time:07-23

student_data = [
    {"name":"Budi", "score": 90},
    {"name":"Nina", "score": 78},
    {"name":"Rudi", "score": 91},
    {"name":"Olivia","score": 76},
    {"name":"Leo", "score": 80},
    {"name":"Liam", "score": 67},
    {"name":"Sheila","score": 76}
   ]

I want to get students name that have score >=80 in the list format. Expected answer :

[Budi, Rudi, Leo]

This is my code that im trying to use but somehow get error message:

for i in range(len(student_data)): 
    if student_data[i].values()>=80:
        print(student_data[i].keys())

Is there any solution?

CodePudding user response:

Try a list comprehension:

result = [dic.get('name') for dic in student_data if dic.get('score')>=80]

Output result:

['Budi', 'Rudi', 'Leo']

CodePudding user response:

Something like this should work

student_data = [ { "name":"Budi", "score": 90 }, { "name":"Nina", "score": 78 }, { "name":"Rudi", "score": 91 }, { "name":"Olivia", "score": 76 }, { "name":"Leo", "score": 80 }, { "name":"Liam", "score": 67 }, { "name":"Sheila", "score": 76 } ]

for i in student_data: 
  if i["score"] >= 80:
    print(i["name"])

CodePudding user response:

You could try this first: (and make it looks nicer List Comp later :-)

Actually, your code is following the right logic, but syntax is off. Generally, it's not recommend to use index (eg. range) to access the item in sequence/Iterable (list, dictionary) because they can be easily accessed directly either in for-loop of key-val way.

# 1. looping the data:  
for item in data:                  # each is a dictionary 
    print(item)
    if item['score'] >= 80:
        print(item['name'])

# 2. Then convert it to List Comprehension: 
ans = [d['name'] for d in data if d['score'] >= 80]
print(ans)            # ['Budi', 'Rudi', 'Leo']   <--good students 

# 3. This is try to *fix* your code: (see the difference?)
out = []

for item  in data:                  # choose some meaningful variable name 
    if item['score'] >= 80:
        out.append(item['name'])    # save the name for output

print(out)

CodePudding user response:

Here's my solution:

new_list = []

for i in range(len(student_data)):
  if student_data[i].get('score') >= 80:
    new_list.append(student_data[i].get('name'))

print(new_list)

Output:

['Budi', 'Rudi', 'Leo']

CodePudding user response:

Try this,

Solution 1: Using filter and lambda,

filtered_data=list(filter(lambda x:x['score']>=80,student_data))
print(filtered_data)

Solution 2: Using List comprehension,

filtered_data=[i for i in student_data if i['score']>=80]
  • Related