Dictionary of attributes

In previous examples (e.g., Do and Environment variables), all the values in the dictionary belonged to the same data type (string). In this example, the values belong to different types. As usual, however, all the keys are still strings.

attributes.py

	age
	citizenship
	favorite years
	leaning
	name
	zipcode

What attribute do you want to see (e.g., name)? name
The attribute name is Mark.

	age
	citizenship
	favorite years
	leaning
	name
	zipcode

What attribute do you want to see (e.g., name)? age
The attribute age is 64.25.

	age
	citizenship
	favorite years
	leaning
	name
	zipcode

What attribute do you want to see (e.g., name)? favorite years
The attribute favorite years is (1968, 2001, 2019).

	age
	citizenship
	favorite years
	leaning
	name
	zipcode

What attribute do you want to see (e.g., name)?

Things to try

  1. If the value of the attribute is a string, print quotes around it. Change lines 28–31 to one of the following. Which one is easier to understand? I like the second one because it cleanly separates the two jobs of
    1. verifying that the key exists; followed by
    2. formatting the value.
    Also, I like having the try and the matching except as close together as possible.
        try:                                             
            value = attributes[key]                      
            if isinstance(value, str):                     
                print(f'The attribute {key} is "{value}".')
            else:                                          
                print(f'The attribute {key} is {value}.')  
        except KeyError:                                 
            print(f'Sorry, "{key}" is not an attribute.')
    
        try:                                             
            value = attributes[key]                      
        except KeyError:                                 
            print(f'Sorry, "{key}" is not an attribute.')
        else:
            #Arrive here if no exception was raised.
            if isinstance(value, str):                      
                print(f'The attribute {key} is "{value]}".')
            else:                                           
                print(f'The attribute {key} is {value}.')   
    
    	age
    	citizenship
    	favorite years
    	leaning
    	name
    	zipcode
    
    What attribute do you want to see (e.g., name)? name
    The attribute name is "Mark".
    
    	age
    	citizenship
    	favorite years
    	leaning
    	name
    	zipcode
    
    What attribute do you want to see (e.g., name)? zipcode
    The attribute zipcode is 10003.
    
    etc.
    
  2. If the value of the attribute is a float, print it with one digit to the right of the decimal point.