Search code examples
pythondictionarytruthtable

Creating dictionary dynamically in Python


I have this list and number:

list = ['B','C']

The outcome that I need for my table is:

B    C    Prob
0    0    x
0    1    x
1    0    x
1    1    x

How can I build this truth table (there can be more vairables, not only 3) and assign a number to that row's probability?

I need to build it with a dictionary, I tried with some list comprehension but I don't know how to generate dynamically the truth table, considering that there can be more/less than 3 variables.

EDIT: to be more clear my goal is to have a dictionary like this:

dict = {"B":0/1,"C":0/1,"Prob":arbitraryNumber}

and I need to insert all these dictionaries into a list to represent the structure of a table, is it clearer now?

Thank you very much


Solution

  • You can generate the truth table using a powerset,

    def power_set(items):
        n = len(items)
        for i in xrange(2**n):
            combo = []
            for j in xrange(n):
                if (i >> j) % 2 == 1:
                    combo.append(1)
                else:
                    combo.append(0)
            yield combo    # if you want tuples, change to yield tuple(combo)
    
    
    In [13]: list(power_set(l))
    Out[13]: [[0, 0], [1, 0], [0, 1], [1, 1]]
    
    In [14]: l=['B','C','E']
    
    In [15]: list(power_set(l))
    Out[15]: 
    [[0, 0, 0],
    [1, 0, 0],
     [0, 1, 0],
     [1, 1, 0],
     [0, 0, 1],
     [1, 0, 1],
     [0, 1, 1],
     [1, 1, 1]]
    

    If you want to make a dict of the data, change yield combo to yield tuple(combo)

    Then you can store key value pairings like:

    d={}
    for data in power_set(l):
        d[data]="your_calc_prob"
    print d
    {(0, 1): 'your_calc_prob', (1, 0): 'your_calc_prob', (0, 0): 'your_calc_prob', (1, 1): 'your_calc_prob'}
    

    If you want the output sorted you can use sorted() which makes a copy of the list and returns a list:

     sorted(list(power_set(l)))
     Out[21]: 
     [[0, 0, 0],
     [0, 0, 1],
     [0, 1, 0],
     [0, 1, 1],
     [1, 0, 0],
     [1, 0, 1],
     [1, 1, 0],
     [1, 1, 1]]
    

    Or you can use the list method sort() which sorts the list in place:

    In [22]: data = list(power_set(l))  
    In [23]: data.sort()
    In [24]: data
    Out[24]: 
    [[0, 0, 0],
    [0, 0, 1],
    [0, 1, 0],
    [0, 1, 1],
    [1, 0, 0],
    [1, 0, 1],
    [1, 1, 0],
    [1, 1, 1]]