1

I have a dictionary consisting of key:[list] in which the list is a fixed and even number of binary values, ie:

{'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}

For each key, I need to return a new value for each pair of values in the original dict, such that for pair(1,1) = 3, pair(0,1) = 2, pair(1,0) = 1, pair(0,0) = 0.

For the example above, output would be:

{'a':[2,1,2],'b':[3,1,0]}

New to both python and programming in general, and haven't found what I'm looking for on SO. Suggestions appreciated.

Rubens
  • 14,478
  • 11
  • 63
  • 92
Thain
  • 245
  • 1
  • 3
  • 9

3 Answers3

1

First attack just the pairing part:

def paired(binlist, map={(1, 1): 3, (0, 1): 2, (1, 0): 1, (0, 0): 0}):
    return [map[tuple(binlist[i:i + 2])] for i in range(0, len(binlist), 2)]

Then apply this to your dictionary:

{k: paired(v) for k, v in input_dictionary.iteritems()}

Demo:

>>> paired([0,1,1,0,0,1])
[2, 1, 2]
>>> paired([1,1,1,0,0,0])
[3, 1, 0]
>>> input_dictionary = {'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}
>>> {k: paired(v) for k, v in input_dictionary.iteritems()}
{'a': [2, 1, 2], 'b': [3, 1, 0]}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

A small snippet I could come up with was :

>>> testDict = {'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}
>>> referenceDict = {(0, 1):2, (0, 0):0, (1, 0):1, (1, 1):3}
>>> for key, value in testDict.items():
        finalList = [referenceDict[elem] for elem in zip(value[::2], value[1::2])]
        testDict[key] = finalList       
>>> testDict
{'a': [2, 1, 2], 'b': [3, 1, 0]}

value[::2] is Python's Slice Notation.

Packing this up into a function for use :

def testFunction(inputDict):
    referenceDict = {(0, 1):2, (0, 0):0, (1, 0):1, (1, 1):3}
    for key, value in inputDict.items():
        finalList = [referenceDict[elem] for elem in zip(value[::2], value[1::2])]
        inputDict[key] = finalList
    return inputDict

Example -

>>> testFunction({'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]})
{'a': [2, 1, 2], 'b': [3, 1, 0]}
Community
  • 1
  • 1
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
0
>>> D = {'a': [0, 1, 1, 0, 0, 1],'b': [1, 1, 1, 0, 0, 0]}
>>> {k: [v[i] + 2 * v[i+1] for i in range(0, len(v), 2)] for k, v in D.items()}
{'a': [2, 1, 2], 'b': [3, 1, 0]}
John La Rooy
  • 295,403
  • 53
  • 369
  • 502