Search code examples
pythondictionaryiterationstring-interpolation

How can I use string interpolation while iterating over a dictionary in python 3?


I have a dictionary full of states and their abbreviations mapped to their actual names. And I want to iterate over them, because I want to make a task easier (don't want to write this out for each state). So far I have a dictionary like this

state_dict = {
    'AK': 'ALASKA',
    'AL': 'ALABAMA',
    'AR': 'ARKANSAS',
    'AS': 'AMERICAN SAMOA',
    'AZ': 'ARIZONA ',
    'CA': 'CALIFORNIA ',
    'CO': 'COLORADO ',
    'CT': 'CONNECTICUT',
    'DC': 'DISTRICT OF COLUMBIA',
    'DE': 'DELAWARE',
    'FL': 'FLORIDA',
    'FM': 'FEDERATED STATES OF MICRONESIA',
    'GA': 'GEORGIA',
    'GU': 'GUAM ',
    'HI': 'HAWAII',
    'IA': 'IOWA',
    'ID': 'IDAHO',
    'IL': 'ILLINOIS',
    'IN': 'INDIANA',
    'KS': 'KANSAS',
    'KY': 'KENTUCKY',
    'LA': 'LOUISIANA',
    'MA': 'MASSACHUSETTS',
    'MD': 'MARYLAND',
    'ME': 'MAINE',
    'MH': 'MARSHALL ISLANDS',
    'MI': 'MICHIGAN',
    'MN': 'MINNESOTA',
    'MO': 'MISSOURI',
    'MP': 'NORTHERN MARIANA ISLANDS',
    'MS': 'MISSISSIPPI',
    'MT': 'MONTANA',
    'NC': 'NORTH CAROLINA',
    'ND': 'NORTH DAKOTA',
    'NE': 'NEBRASKA',
    'NH': 'NEW HAMPSHIRE',
    'NJ': 'NEW JERSEY',
    'NM': 'NEW MEXICO',
    'NV': 'NEVADA',
    'NY': 'NEW YORK',
    'OH': 'OHIO',
    'OK': 'OKLAHOMA',
    'OR': 'OREGON',
    'PA': 'PENNSYLVANIA',
    'PR': 'PUERTO RICO',
    'RI': 'RHODE ISLAND',
    'SC': 'SOUTH CAROLINA',
    'SD': 'SOUTH DAKOTA',
    'TN': 'TENNESSEE',
    'TX': 'TEXAS',
    'UT': 'UTAH',
    'VA': 'VIRGINIA ',
    'VI': 'VIRGIN ISLANDS',
    'VT': 'VERMONT',
    'WA': 'WASHINGTON',
    'WI': 'WISCONSIN',
    'WV': 'WEST VIRGINIA',
    'WY': 'WYOMING'
}

for k, v in state_dict.items():
    print("""if (c_state_code.equals("{k}"))
               {
                   out_state_code = "{v}";
               }""").format(k, v)

But I'm getting 'NoneType' object has no attribute 'format, and I even tried **attrs in the .format but got the same error.


Solution

  • You're calling format() on the result of print(), which doesn't return anything. It should be called on the format string -- it needs to be inside the argument to print().

    for k, v in state_dict.items():
       print("""if (c_state_code.equals("{k}"))
                  {{
                      out_state_code = "{v}";
                  }}""".format(k, v))
    

    If you're using Python version 3.6 you can make it even easier using an f-string.

    for k, v in state_dict.items():
       print(f"""if (c_state_code.equals("{k}"))
                  {{
                      out_state_code = "{v}";
                  }}""")