-1

Having dictionary with family members how can I create a tree of it?

Dictionary have a structure that looks like this:

{'parent':'Smith', 'children':[
    {'parent':'Connor', 'children':[
        {'parent':'Alexis','children':[
            {'parent':'Joe', 'children':[
                {'parent':'Clark','children':[]}]}]},
        {'parent':'Sue','children':[]}]},
    {'parent':'Cooper', 'children':[
        {'parent':'Max','children':[
            {'parent':'Luis', 'children':[]},]},
        {'parent':'Elvis', 'children':[]},
        {'parent':'Steven', 'children':[]}]}]}

After creating family tree, how can I check some dates such as: how to check how many members got entire family or single family of tree.

check how big is entire family tree root or some part of family.

how can I add new members to existing position or to new position inside family tree?

Edit

Adding example of tree:

Smith
    Conor
        Alexis
            Joe
                Clark
        Sue
    Cooper
        Max
            Luis
        Elvis
        Steven

Same style as computer system directory.

Infinity00
  • 9
  • 1
  • 1
  • 6
  • 1
    Why do you think the dict is not already a tree? What do you mean by tree? – Ray Toal Dec 02 '12 at 16:21
  • 2
    Dude, your `dict` is already a tree. What do you want in your "tree" that's not already implemented in the `dict`? – inspectorG4dget Dec 02 '12 at 16:32
  • Thanks for adding the example, but the example is just a list of (indented) strings. It is not hard to go through the dictionary and print strings, but if your question is how to make a tree data structure, then I still submit you already have it. – Ray Toal Dec 02 '12 at 16:35
  • I think the OP just wants a visual format. –  Dec 02 '12 at 16:36
  • there seems to be a missing or wrong } or ] in the dictionary somewhere, please check it. – Stuart Dec 02 '12 at 16:43
  • @RayToal, well, I'm trying to solve some exercises from the book. it ask for creating a tree having such dictionary and adding some functions like counter of all members or sinly root of tree, adding new members, getting tree root and so on. – Infinity00 Dec 02 '12 at 16:47
  • @Stuart, I'm sorry, fixed. try again – Infinity00 Dec 02 '12 at 16:55
  • @RayToal, I didnt pay attention when i was reading text,im sorry, yes it ask for visual format and to make 1 `treeNodes(object)` and 1 `def createTree`, and such options which I did write in post, sorry again for not giving all informations... :S – Infinity00 Dec 02 '12 at 17:45

2 Answers2

2

This is just inspectorG4dget's answer which was almost there but needs some alterations:

class Person:
    ID = itertools.count()
    def __init__(self, name, parent=None, level=0):
        self.id = self.__class__.ID.next() # next(self.__class__.ID) in python 2.6+
        self.parent = parent
        self.name = name
        self.level = level
        self.children = []

def createTree(d, parent=None, level=0):
    if d:
        member = Person(d['parent'], parent, level)
        level = level + 1
        member.children = [createTree(child, member, level) for child in d['children']]
        return member

t = createTree(my_tree)          # my_tree is the name of your dictionary
def printout(parent, indent=0):
    print '\t'*indent, parent.name
    for child in parent.children:
        printout(child, indent+1)        
printout(t)

As per the comment above, you need to import itertools at the beginning of the programme.

EDIT: A function to flatten the tree should serve for everything else you want to do:

def flatten(parent):
    L = [parent]
    for child in parent.children:
        L += flatten(child)
    return L
flattened_tree = flatten(t)
print "All members: ", [person.name for person in flattened_tree]
print "Number of members:", len(flattened_tree)
print "Number of levels:", max([person.level for person in flattened_tree]) + 1
cooper = flattened_tree[6]
cooper_fl = flatten(cooper)
print "Members below Cooper: ", [person.name for person in cooper_fl]
print "Number:", len(cooper_fl)
levels = [person.level for person in cooper_fl]
print "Number of levels:", max(levels) - min(levels) + 1
Stuart
  • 8,399
  • 1
  • 17
  • 30
  • they should implement like button like on facebook heh... it working :) what about when I want add new member to family tree? `t.count()` -> 11 counted all memebers of tree `t.root()` -> 5 max tree root of full family is 5. `t.children()[0].count()` -> 5 children in all `t.children()[1].root()` -> 3 starting from `cooper` and ending in `luis` – Infinity00 Dec 02 '12 at 18:26
  • uh, there is an up arrow to the left that works a lot like 'like' on facebook! Also you can accept the answer. – Stuart Dec 02 '12 at 18:30
  • ah, I just finished to read rules of this wonderful site, i can choose only 1 correct answer :s ur or inspectorG4dget? could u check and tell me how to add those options to class, please? – Infinity00 Dec 02 '12 at 18:46
  • not print but `function (def)` which will give u as result those prints :P that `cooper` was just an example :) going to accept ur answer and make him +1? – Infinity00 Dec 02 '12 at 19:13
  • did! :) , one last question what is difference between `class first(object):` and `class second:` 10 more exercies to do :S – Infinity00 Dec 02 '12 at 20:06
  • The first is 'new-style' and is usually preferred. As far as I know it makes no difference in the above example. http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python – Stuart Dec 02 '12 at 20:36
0

Untested, but this should do it

class Person:
    ID = itertools.count()
    def __init__(self):
        self.id = next(self.__class__.ID)
        self.parent = None
        self.children = []

def createTree(familyTreeDict, parent=None):
    if not familyTreeDict:
        return []
    else:
        members = []
        for name familyTreeDict:
            members.append(Person(name))
            members[-1].parent = parent
            for child in familyTreeDict[name]:
                members[-1].children.append(createTree(child, members[-1]))
        return members

Then, if you want to print out a tree structure, given the output from createTree:

def printout(family, indent=0):
    for parent in family:
        print '\t'*indent, parent.name
        for child in parent.children:
            printout(child, indent+1)

Hope this helps

inspectorG4dget
  • 104,525
  • 25
  • 135
  • 234
  • getting error: `ID = itertools.count() NameError: name 'itertools' is not defined` and in `for name familyTreeDict:` you forgot to add `in` – Infinity00 Dec 02 '12 at 17:39
  • import itertools....and you should probably read some more docs on python.org if that bit threw you a curveball – Chrismit Dec 02 '12 at 17:55
  • im beginner in coding world and python is my first scripting leangueg. :( after imported `itertool` and tried to `printout` it gives me error `printout(d)`, `d` is var of all family tree:` print '\t'*indent, parent.name AttributeError: 'str' object has no attribute 'name'` – Infinity00 Dec 02 '12 at 18:16