US states named tuple (Python)

vegaseat 2 Tallied Votes 668 Views Share

Just a little fun with Python's named tuple, behaves like a class but is much leaner.

''' namedtuple_US_states1.py
use a data string (potential csv file with ; separator)
to create a named tuple of US states
tested with Python27 and Python33  by  vegaseat  17sep2013
'''

from collections import namedtuple
import pprint

# each line (use ; as separator since date contains a comma)
# state;capital;joined union at date;flower;bird
data_str = """\
Alabama;Montgomery;December 14, 1819;Camellia;Yellowhammer
Alaska;Juneau;January 3, 1959;Forget-me-not;Willow Ptarmigan
Arizona;Phoenix;February 14, 1912;Suguaro Cactus Blossom;Cactus Wren
Arkansas;Little Rock;June 15, 1836;Apple Blossom;Mockingbird
California;Sacremento;September 9, 1850;Golden Poppy;California Valley Quail
Colorado;Denver;August 1, 1876;Mountain Columbine;Lark Bunting
Connecticut;Hartford;January 9, 1788;Mountain Laurel;Robin
Delaware;Dover;December 7, 1787;Peach Blossom;Blue Hen Chicken
Florida;Tallahassee;March 3, 1845;Orange Blossom;Mockingbird
Georgia;Atlanta;January 2, 1788;Cherokee Rose;Brown Thrasher
Hawaii;Honolulu;August 21, 1959;Red Hibiscus;Nene (Hawaiian Goose)
Idaho;Boise;July 3, 1890;Syringa;Mountain Bluebird
Illinois;Springfield;December 3, 1818;Violet;Cardinal
Indiana;Indianapolis;December 11, 1816;Peony;Cardinal
Iowa;Des Moines;December 28, 1846;Wild Rose;Eastern Goldfinch
Kansas;Topeka;January 29, 1861;Sunflower;Western Meadowlark
Kentucky;Frankfort;June 1, 1792;Goldenrod;Cardinal
Louisiana;Baton Rouge;April 30, 1812;Magnolia;Eastern Brown Pelican
Maine;Augusta;March 15, 1820;Pine Cone & Tassel;Chickadee
Maryland;Annapolis;April 28, 1788;Black-eyed Susan;Baltimore Oriole
Massachusetts;Boston;February 6, 1788;Mayflower;Chickadee
Michigan;Lansing;January 26, 1837;Apple Blossom;Robin
Minnesota;St. Paul;May 11, 1858;Lady-slipper;Loon
Mississippi;Jackson;December 10, 1817;Magnolia;Mockingbird
Missouri;Jefferson City;August 10, 1821;Hawthorn;Bluebird
Montana;Helena;November 8, 1889;Bitterroot;Western Meadowlark
Nebraska;Lincoln;March 1, 1867;Goldenrod;Western Meadowlark
Nevada;Carson City;October 31, 1864;Sagebrush;Mountain Bluebird
New Hampshire;Concord;June 21, 1788;Purple Lilac;Purple Finch
New Jersey;Trenton;December 18, 1787;Violet;Eastern Goldfinch
New Mexico;Santa Fe;January 6, 1912;Yucca;Road Runner
New York;Albany;July 26, 1788;Rose;Bluebird
North Carolina;Raleigh;November 21, 1789;Flowering Dogwood;Cardinal
North Dakota;Bismarck;November 2, 1889;Prairie Rose;Meadowlark
Ohio;Columbus;March 1, 1803;Scarlet Carnation;Cardinal
Oklahoma;Oklahoma City;November 16, 1907;Mistletoe;Scissor-tailed Flycatcher
Oregon;Salem;February 14, 1859;Oregon Grape;Western Meadowlark
Pennsylvania;Harrisburg;December 12, 1787;Mountain Laurel;Ruffed Grouse
Rhode Island;Providence;May 29, 1790;Violet;Rhode Island Red
South Carolina;Columbia;May 23, 1788;Yellow Jessamine;Carolina Wren
South Dakota;Pierre;November 2, 1889;Pasqueflower;Ring-necked Pheasant
Tennessee;Nashville;June 1, 1796;Iris;Mockingbird
Texas;Austin;December 29, 1845;Bluebonnet;Mockingbird
Utah;Salt Lake City;January 4, 1896;Sego Lily;Sea Gull
Vermont;Montpelier;March 4, 1791;Red Clover;Hermit Thrush
Virginia;Richmond;June 26, 1788;Dogwood;Cardinal
Washington;Olympia;November 11, 1889;Coast Rhododendron;Willow Goldfinch
West Virginia;Charleston;June 20, 1863;Rhododendron;Cardinal
Wisconsin;Madison;May 29, 1848;Wood Violet;Robin
Wyoming;Cheyenne;July 10, 1890;Indian Paintbrush;Meadowlark
"""

# create a list of [state, capital, date, flower, bird] lists
# sort by state name just to make sure
data_list = sorted(line.split(';') for line in data_str.split('\n') if line)

#pprint.pprint(data_list)  # test

# named tuple States behaves like a class, and has much less overhead
States = namedtuple('States', 'state capital date flower bird')

# create a list of instances
instance_list = [States(state, capital, date, flower, bird)\
             for state, capital, date, flower, bird in data_list]

#pprint.pprint(instance_list)  # test
#print('-'*35)

# show the states where the state bird is a "Robin"
bird = "Robin"
print("States with {} as state bird:".format(bird))
for state in instance_list:
    if state.bird == bird:
        print(state.state)

print('-'*35)

# show the states where the state flower is a "Apple Blossom"
flower = "Apple Blossom"
print("States with {} as state flower:".format(flower))
for state in instance_list:
    if state.flower == flower:
        print(state.state)

print('-'*35)

first = 'M'
print("All the states that start with '{}':".format(first))
for state in instance_list:
    if state.state[0] == first:
        print(state.state)

print('-'*35)

print("All US states and their capitals:")
for state in instance_list:
    print("{:15} {}".format(state.state, state.capital))

''' result ...
States with Robin as state bird:
Connecticut
Michigan
Wisconsin
-----------------------------------
States with Apple Blossom as state flower:
Arkansas
Michigan
-----------------------------------
All the states that start with 'M':
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
-----------------------------------
All US states and their capitals:
Alabama         Montgomery
Alaska          Juneau
Arizona         Phoenix
Arkansas        Little Rock
California      Sacremento
Colorado        Denver
Connecticut     Hartford
Delaware        Dover
Florida         Tallahassee
Georgia         Atlanta
Hawaii          Honolulu
Idaho           Boise
Illinois        Springfield
Indiana         Indianapolis
Iowa            Des Moines
Kansas          Topeka
Kentucky        Frankfort
Louisiana       Baton Rouge
Maine           Augusta
Maryland        Annapolis
Massachusetts   Boston
Michigan        Lansing
Minnesota       St. Paul
Mississippi     Jackson
Missouri        Jefferson City
Montana         Helena
Nebraska        Lincoln
Nevada          Carson City
New Hampshire   Concord
New Jersey      Trenton
New Mexico      Santa Fe
New York        Albany
North Carolina  Raleigh
North Dakota    Bismarck
Ohio            Columbus
Oklahoma        Oklahoma City
Oregon          Salem
Pennsylvania    Harrisburg
Rhode Island    Providence
South Carolina  Columbia
South Dakota    Pierre
Tennessee       Nashville
Texas           Austin
Utah            Salt Lake City
Vermont         Montpelier
Virginia        Richmond
Washington      Olympia
West Virginia   Charleston
Wisconsin       Madison
Wyoming         Cheyenne
'''
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Now here is a brain teaser, list all the states that joined the Union after 1865.

BearofNH 104 Posting Whiz

Now here is a brain teaser, list all the states that joined the Union after 1865

Add the following to the end:

print('-'*35)

print("US states admitted after 1865:")
for state in instance_list:
    if int(state.date[-4:]) > 1865:
        print("{:15} {}".format(state.state, state.date[-4:]))

Works for me ...

BearofNH 104 Posting Whiz

Oops, the output is:

    -----------------------------------
    US states admitted after 1865:
    Alaska          1959
    Arizona         1912
    Colorado        1876
    Hawaii          1959
    Idaho           1890
    Montana         1889
    Nebraska        1867
    New Mexico      1912
    North Dakota    1889
    Oklahoma        1907
    South Dakota    1889
    Utah            1896
    Washington      1889
    Wyoming         1890
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Another brain teaser. Can you turn this snippet into a Quiz with multiple choices?

BearofNH 104 Posting Whiz

For Python 2.7:

''' -- Mode: Python; tab-width: 4; python-indent: 4; indent-tabs-mode: nil -- '''

''' namedtuple_US_states1.py
use a data string (potential csv file with ; separator)
to create a named tuple of US states
tested with Python27 and Python33 by vegaseat 17sep2013
'''


from collections import namedtuple
import pprint
import random
from sys import exit

# each line (use ; as separator since date contains a comma)
# state;capital;joined union at date;flower;bird
data_str = """\
Alabama;Montgomery;December 14, 1819;Camellia;Yellowhammer
Alaska;Juneau;January 3, 1959;Forget-me-not;Willow Ptarmigan
Arizona;Phoenix;February 14, 1912;Suguaro Cactus Blossom;Cactus Wren
Arkansas;Little Rock;June 15, 1836;Apple Blossom;Mockingbird
California;Sacremento;September 9, 1850;Golden Poppy;California Valley Quail
Colorado;Denver;August 1, 1876;Mountain Columbine;Lark Bunting
Connecticut;Hartford;January 9, 1788;Mountain Laurel;Robin
Delaware;Dover;December 7, 1787;Peach Blossom;Blue Hen Chicken
Florida;Tallahassee;March 3, 1845;Orange Blossom;Mockingbird
Georgia;Atlanta;January 2, 1788;Cherokee Rose;Brown Thrasher
Hawaii;Honolulu;August 21, 1959;Red Hibiscus;Nene (Hawaiian Goose)
Idaho;Boise;July 3, 1890;Syringa;Mountain Bluebird
Illinois;Springfield;December 3, 1818;Violet;Cardinal
Indiana;Indianapolis;December 11, 1816;Peony;Cardinal
Iowa;Des Moines;December 28, 1846;Wild Rose;Eastern Goldfinch
Kansas;Topeka;January 29, 1861;Sunflower;Western Meadowlark
Kentucky;Frankfort;June 1, 1792;Goldenrod;Cardinal
Louisiana;Baton Rouge;April 30, 1812;Magnolia;Eastern Brown Pelican
Maine;Augusta;March 15, 1820;Pine Cone & Tassel;Chickadee
Maryland;Annapolis;April 28, 1788;Black-eyed Susan;Baltimore Oriole
Massachusetts;Boston;February 6, 1788;Mayflower;Chickadee
Michigan;Lansing;January 26, 1837;Apple Blossom;Robin
Minnesota;St. Paul;May 11, 1858;Lady-slipper;Loon
Mississippi;Jackson;December 10, 1817;Magnolia;Mockingbird
Missouri;Jefferson City;August 10, 1821;Hawthorn;Bluebird
Montana;Helena;November 8, 1889;Bitterroot;Western Meadowlark
Nebraska;Lincoln;March 1, 1867;Goldenrod;Western Meadowlark
Nevada;Carson City;October 31, 1864;Sagebrush;Mountain Bluebird
New Hampshire;Concord;June 21, 1788;Purple Lilac;Purple Finch
New Jersey;Trenton;December 18, 1787;Violet;Eastern Goldfinch
New Mexico;Santa Fe;January 6, 1912;Yucca;Road Runner
New York;Albany;July 26, 1788;Rose;Bluebird
North Carolina;Raleigh;November 21, 1789;Flowering Dogwood;Cardinal
North Dakota;Bismarck;November 2, 1889;Prairie Rose;Meadowlark
Ohio;Columbus;March 1, 1803;Scarlet Carnation;Cardinal
Oklahoma;Oklahoma City;November 16, 1907;Mistletoe;Scissor-tailed Flycatcher
Oregon;Salem;February 14, 1859;Oregon Grape;Western Meadowlark
Pennsylvania;Harrisburg;December 12, 1787;Mountain Laurel;Ruffed Grouse
Rhode Island;Providence;May 29, 1790;Violet;Rhode Island Red
South Carolina;Columbia;May 23, 1788;Yellow Jessamine;Carolina Wren
South Dakota;Pierre;November 2, 1889;Pasqueflower;Ring-necked Pheasant
Tennessee;Nashville;June 1, 1796;Iris;Mockingbird
Texas;Austin;December 29, 1845;Bluebonnet;Mockingbird
Utah;Salt Lake City;January 4, 1896;Sego Lily;Sea Gull
Vermont;Montpelier;March 4, 1791;Red Clover;Hermit Thrush
Virginia;Richmond;June 26, 1788;Dogwood;Cardinal
Washington;Olympia;November 11, 1889;Coast Rhododendron;Willow Goldfinch
West Virginia;Charleston;June 20, 1863;Rhododendron;Cardinal
Wisconsin;Madison;May 29, 1848;Wood Violet;Robin
Wyoming;Cheyenne;July 10, 1890;Indian Paintbrush;Meadowlark
"""
# create a list of [state, capital, date, flower, bird] lists
# sort by state name just to make sure
data_list = sorted(line.split(';') for line in data_str.split('\n') if line)
#pprint.pprint(data_list) # test
# named tuple States behaves like a class, and has much less overhead
States = namedtuple('States', 'state capital date flower bird')
# create a list of instances
instance_list = [States(state, capital, date, flower, bird)\
                 for state, capital, date, flower, bird in data_list]


# Bird names not found in instance_list, mostly for humor's sake.
#
hokum = ("Bald Eagle", "Mosquito", "Pterodactyl", "Dodo bird", "Condor", "Carolina Parakeet", \
             "Bay Thrush", "Elf Owl", "White-mantled Barbet", "Spectacled Cormorant", "Titmouse")


def gen_bird_list(how_many, avoid):
    'Generate a list [] of "how_many" birds that are NOT the same as "avoid" (the right answer)'
    retlst = []                 # List to return

    if random.randint(1,10) == 1: # Occasionally toss in a hokey bird name
        retlst.append(random.sample(hokum,1)[0])

    # Build the return list one element at a time.
    #
    while len(retlst) < how_many:
        birdie = random.sample(instance_list,1)[0].bird # Pick a bird
        if birdie not in retlst and \
           birdie != avoid:     # Skipping duplicates and mandated avoidance
            retlst.append(birdie)

    return retlst


if __name__ == "__main__":

    legal_picks = 'abcde'
    r5 = range(5)
    already_asked = []                                      # States we've already asked about
    right = 0                                               # Count of right answers
    wrong = 0                                               # Count of wrong answers
    qcount = 10
    while len(already_asked) < qcount:  # Keep asking questions until we hit 10

        right_answer_x = random.randint(0, len(instance_list)-1) # Index of right answer
        right_answer_i = instance_list[right_answer_x]           # Instance of right answer
        right_answer_s = right_answer_i.state                    # State of right answer
        right_answer_b = right_answer_i.bird                     # Bird  of right answer

        if right_answer_x in already_asked: # If we asked about this state before,
            continue                        #  don't ask again this time

        already_asked.append(right_answer_x)
        choices = gen_bird_list(4, right_answer_b)
        choices.append(right_answer_b)
        random.shuffle(choices)

        #print "For", right_answer_s, "choices:", choices, "right answer =", right_answer_b

        while True:                 # Until we get a valid pick
            print
            print "%d/%d. What is the state bird of %s?" % (len(already_asked),qcount,right_answer_s)
            for i in r5:
                print '\t(%s)' % legal_picks[i], choices[i]
            print 'Your choice:',
            pick = raw_input()
            if len(pick) != 1 or pick not in legal_picks:
                print "Please enter a single letter, one of a,b,c,d,e"
                continue
            else:
                i = legal_picks.index(pick)
                break

        if choices[i] == right_answer_b:
            print "Correct! The %s is the state bird of %s" % (right_answer_b, right_answer_s)
            right += 1
        else:
            print "Sorry, the %s is not the state bird of %s." % (choices[i], right_answer_s)
            print "Right answer:", right_answer_b
            wrong += 1

        print "Moving on ..."
    total = right + wrong
    if total > 0:
        print "You got %d right out of %d, or %.0f%%" % (right, total, 100.0*right/total)

TEST RUN

C:\>usstates.py

1/10. What is the state bird of New York?
        (a) Willow Goldfinch
        (b) Mockingbird
        (c) Cactus Wren
        (d) Cardinal
        (e) Bluebird
Your choice: d
Sorry, the Cardinal is not the state bird of New York.
Right answer: Bluebird
Moving on ...

2/10. What is the state bird of Wyoming?
        (a) Meadowlark
        (b) Scissor-tailed Flycatcher
        (c) Pterodactyl
        (d) Mountain Bluebird
        (e) Brown Thrasher
Your choice: a
Correct! The Meadowlark is the state bird of Wyoming
Moving on ...

3/10. What is the state bird of Maine?
        (a) Chickadee
        (b) Scissor-tailed Flycatcher
        (c) Cardinal
        (d) Bluebird
        (e) Western Meadowlark
Your choice: a
Correct! The Chickadee is the state bird of Maine
Moving on ...

4/10. What is the state bird of Alaska?
        (a) Willow Ptarmigan
        (b) Lark Bunting
        (c) Mockingbird
        (d) Meadowlark
        (e) Willow Goldfinch
Your choice: a
Correct! The Willow Ptarmigan is the state bird of Alaska
Moving on ...

5/10. What is the state bird of Florida?
        (a) Ring-necked Pheasant
        (b) Road Runner
        (c) California Valley Quail
        (d) Bluebird
        (e) Mockingbird
Your choice: d
Sorry, the Bluebird is not the state bird of Florida.
Right answer: Mockingbird
Moving on ...

6/10. What is the state bird of Tennessee?
        (a) Eastern Brown Pelican
        (b) Chickadee
        (c) Road Runner
        (d) Western Meadowlark
        (e) Mockingbird
Your choice: b
Sorry, the Chickadee is not the state bird of Tennessee.
Right answer: Mockingbird
Moving on ...

7/10. What is the state bird of Missouri?
        (a) Purple Finch
        (b) Bluebird
        (c) California Valley Quail
        (d) Western Meadowlark
        (e) Mockingbird
Your choice: b
Correct! The Bluebird is the state bird of Missouri
Moving on ...

8/10. What is the state bird of Minnesota?
        (a) Loon
        (b) Mountain Bluebird
        (c) Dodo bird
        (d) Blue Hen Chicken
        (e) Carolina Wren
Your choice: a
Correct! The Loon is the state bird of Minnesota
Moving on ...

9/10. What is the state bird of Rhode Island?
        (a) Cardinal
        (b) Rhode Island Red
        (c) Meadowlark
        (d) Robin
        (e) Road Runner
Your choice: b
Correct! The Rhode Island Red is the state bird of Rhode Island
Moving on ...

10/10. What is the state bird of California?
        (a) Cardinal
        (b) Ring-necked Pheasant
        (c) Meadowlark
        (d) California Valley Quail
        (e) Cactus Wren
Your choice: d
Correct! The California Valley Quail is the state bird of California
Moving on ...
You got 7 right out of 10, or 70%

C:\>
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Wow BearofNH, great coding and fun to play.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.