Search code examples
pythondictionarypython-itertools

Missed values when creating a dictionary with two values


I have two lists as follows.

count = (1, 0, 0, 2, 0, 0, 1, 1, 1, 2)
bins = [[2.0, 3.0], [3.0, 4.0], [4.0, 5.0], [5.0, 6.0], [6.0, 7.0], [7.0, 8.0], [8.0, 9.0], [9.0, 10.0], [10.0, 11.0], [11.0, 12.0], [12.0]]

I tried to create a dictionary using following;

dictionary = dict(itertools.izip(count, bins))

And it gives me {"0": [7.0, 8.0], "1": [10.0, 11.0], "2": [11.0, 12.0]}

It gives only the unique key values only but I need to get the all the pairs as below.

{"0": [3.0, 4.0],"0": [4.0, 5.0],"0": [6.0, 7.0],"0": [7.0, 8.0], "1": [2.0, 3.0],"1": [8.0, 9.0], "1": [9.0, 10.0], "1": [10.0, 11.0], "2": [6.0, 7.0] ,"2": [11.0, 12.0]}

or interchange of keys and values in the above dictionary is acceptable.(because keys should be unique) How can I do that?


Solution

  • You can't use a list as a key to a dictionary as it is mutable.

    You could convert the list to a tuple:

    >>> count = (1, 0, 0, 2, 0)
    >>> bins = [[2.0, 3.0], [3.0, 4.0], [4.0, 5.0], [5.0, 6.0], [6.0, 7.0], [7.0, 8.0]]
    
    >>> {tuple(key): value for (key, value) in zip(bins, count)}
    {(4.0, 5.0): 0,
     (3.0, 4.0): 0,
     (5.0, 6.0): 2,
     (2.0, 3.0): 1,
     (6.0, 7.0): 0}
    

    If you want to serialise to json, the keys need to be strings. You could convert the bins to strings instead:

    >>> {str(key): value for (key, value) in zip(bins, count)}
    {'[2.0, 3.0]': 1, '[4.0, 5.0]': 0, '[6.0, 7.0]': 0, '[5.0, 6.0]': 2, '[3.0, 4.0]': 0}
    
    >>> import json
    >>> json.dumps(_)
    '{"[2.0, 3.0]": 1, "[4.0, 5.0]": 0, "[6.0, 7.0]": 0, "[5.0, 6.0]": 2, "[3.0, 4.0]": 0}'
    

    Alternatively, just serialise the pairs, and make the dictionary on the receiving end:

    >>> zip(bins, count)
    [([2.0, 3.0], 1), ([3.0, 4.0], 0), ([4.0, 5.0], 0), ([5.0, 6.0], 2), ([6.0, 7.0], 0)]
    
    >>> import json
    >>> json.dumps(_)
    '[[[2.0, 3.0], 1], [[3.0, 4.0], 0], [[4.0, 5.0], 0], [[5.0, 6.0], 2], [[6.0, 7.0], 0]]'