2

I am trying to print the key and value from a list of dictionaries, and I want the output to appear like this.

first_name - Michael, last_name - Jordan
first_name - John, last_name - Rosales
first_name - Mark, last_name - Guillen
first_name - KB, last_name - Tonel 

this is the code I wrote

students = [
         {'first_name':  'Michael', 'last_name' : 'Jordan'},
         {'first_name' : 'John', 'last_name' : 'Rosales'},
         {'first_name' : 'Mark', 'last_name' : 'Guillen'},
         {'first_name' : 'KB', 'last_name' : 'Tonel'}
    ]
def listd (somelist):
    for key , value in students:
        print(key, '-', value)
print (listd(students))

and i get the output with only keys not values

first_name - last_name
first_name - last_name
first_name - last_name
first_name - last_name
None

what is the mistake I made and how can I view both keys and values?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 2
    You use `.items()` to access (key,value) pairs in dictionaries in python. Beyond that, it's hard to know how to help because your code is not reproducible – G. Anderson May 25 '21 at 17:49
  • tldr use for ... in, just like with JS
    https://stackoverflow.com/questions/5904969/how-to-print-a-dictionarys-key
    – Alan Kersaudy May 25 '21 at 17:49

2 Answers2

1

for sub in students:

 for key,values in sub.items():

     Print(key, " : ", value)

Just extract each sub dictionary from list and call item method of dictionary on each sub dictionary in loop.unpack the key value tuple and you can play with them as you want..

Ashish Nautiyal
  • 861
  • 6
  • 8
0

students is a list. You need to iterate over this list to get each dictionary. Then, for each dictionary, you need to iterate over its key-value pairs to format them the way you want using an f-string. Then, you can use str.join() to join these values with commas to print what you want.

for student in students:
    to_print = []
    for key, value in student.items():
        to_print.append(f"{key} - {value}")

    # Now, to_print is a list that contains two elements:
    # ["first_name - Michael", "last_name - Jordan"]
    print(", ".join(to_print))

which gives:

first_name - Michael, last_name - Jordan
first_name - John, last_name - Rosales
first_name - Mark, last_name - Guillen
first_name - KB, last_name - Tonel

The fancy one-liner:

print(*(", ".join(f"{key} - {value}" for key, value in student.items()) for student in students), sep="\n")
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70