#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    8
    Rep Power
    0

    Nesting a dictionary


    Okay, so it's Christmas day and I'm back for more..

    One of the challenges in the book I'm reading asked to create a dictionary with a son/father/grandfather. Obviously some nesting is involved.

    I successfully created a program where you could find out the father of the son but now that I'm introducing the grandfather into the equation I'm a little stuck. Not exactly sure how to properly nest the dictionary and then calling up the grandfather in the dictionary.

    I've also noticed that when you try to pull up the father,
    it prints the father and grandfather complete with the {:}

    Here's my best attempt:

    Code:
    #the who's your daddy program
    #allow a user to enter the name of a male and the program will produce the name
    #of his father, also add, replace, or delete father/son pairs
    
    #v2.0 nesting grandfathers into the dictionary
    
    #the dictionary
    fathersnsons = {"Luke" : {"Darth Vader" : {"The Chancellor"}},
                    "Neal" : {"Les" : {"Joseph"}},
                    "George" : {"Fred" : {"Mickey"}},
                    "Robert" : {"Tim" : {"Michael"}},
                    "Juan" : {"Hunter" : {"Thompson"}}}
    
    print("                 The Father and Son Dictionary")
    print(
    """
    Welcome to the Father and Son Dictionary. You can enter the name
    of someone to find out who their father is or you can enter,
    delete, or replace a father and son pair in the dictionary.
    
    To find out the father of a male, press "1"
    
    Add a father and son pair to the dictionary, press "2"
    
    Replace a pair, press "3"
    
    Delete a pair, press "4"
    
    Find out the grandfather of a male, press "5"
    
    Quit, press "6"
    """
    )
    
    choice = input("\nEnter a choice: ")
    
    #looking up a father/son combo
    if choice == "1":
        theson = input("Whose dad would you like to find? ")
        if theson in fathersnsons:
            thedad = fathersnsons[theson]
            print("\nThe father of", theson, "is", thedad)
        else:
            print("I'm sorry,", theson, "doesn't have a father.")
    
    #adding a father/son combo
    elif choice == "2":
        theson = input("Enter the name of someone whose father you'd like to add: ")
        if theson not in fathersnsons:
            thedad = input("Who is the father? ")
            fathersnsons[theson] = thedad
            print("\nThe father of", theson, "has been added.")
        else:
            print("\nThe father of", theson, "is already in our database!")
    
    #modifying someone's dad
    elif choice == "3":
        theson = input("Whose dad would you like to change? ")
        if theson in fathersnsons:
            thedad = input("Who's the new dad? ")
            fathersnsons[theson] = thedad
            print("\nThe new father of", theson, "is now", thedad)
        else:
            print("I have no record of", theson, "on file, trying adding him!")
    
    #deleting a father/son combo
    elif choice == "4":
        theson = input("Who would you like to remove from our records? ")
        if theson in fathersnsons:
            del fathersnsons[theson]
            print("\nOkay,", theson, "has been removed from our records.")
        else:
            print("\nIs not in the system!")
    
    #looking up a grandfather
    elif choice == "5":
        theson = input("Whose granddad would you like to find? ")
        if theson in fathersnsons:
            granddad = fathersnsons[theson[1]]
            print("\nThe grandfather of", theson, "is", granddad)
        else:
            print("I'm sorry,", theson, "doesn't have a grandfather.")
    
    #exiting the program
    else:
        input("\nGood-bye")
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,997
    Rep Power
    481
    Merry Christmas!
    Your structure is backward, unless my dyslexia is kicking in.

    Father has son. 1 to many relationship. Thus we look to the Bible for our human family tree:
    Code:
    >>> tree={'Adam': {'Cain': None, 'Abel':None, 'Seth': {'Enos': None}}}
    >>> print("Adam's sons "+', '.join(tree['Adam'].keys()))
    Adam's sons Cain, Abel, Seth
    >>>
    Good God that's confusing! I made 5 syntax errors before I got those two statements to work.

    And please, follow the Bible link above.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    530
    Rep Power
    34
    You want more of a linked list approach I think. That is you only have to input the father and son pairs. You can go one level down and print the grandsons or use recursion to print great-grandsons, great-great-grandsons, etc.
    Code:
    tree={'Adam': ['Cain', 'Abel', 'Seth']}
    tree['Seth']=['Enos', 'Seth Jr.']
    tree['Cain']=["Cain's son"]
    
    adams_sons = tree['Adam']
    print "Adam's sons", ', '.join(adams_sons)
    print "\n----- Adam's grandsons -----"
    for son in adams_sons:
        print son
        if son in tree:
            print "     ", ', '.join(tree[son])
    Last edited by dwblas; December 25th, 2012 at 04:48 PM.

IMN logo majestic logo threadwatch logo seochat tools logo