Home > front end >  How to use a for loop to display the type of each value stored against each key in dictionary?
How to use a for loop to display the type of each value stored against each key in dictionary?

Time:06-14

person = {'Name':'Dustin','Age':19,'HasCar':True}

How can I get the following output using for loop:

The key "Name" has the value "Dustin" of the type "<class 'str'>"
  

CodePudding user response:

use items() function to get both key and value like this

person = {'name':'Dustin','Age':19,'HasCar':True}
for key,val in person.items():
    print(f'The key "{key}" has the value "{val}" of the type "{type(val)}"')

output

The key "name" has the value "Dustin" of the type "<class 'str'>"

The key "Age" has the value "19" of the type "<class 'int'>"

The key "HasCar" has the value "True" of the type "<class 'bool'>"

  • Related