Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 261
Manura Omal Avatar asked Nov 18 '15 06:11

Manura Omal


2 Answers

{"0": [3.0, 4.0],"0": [4.0, 5.0]} is not a valid dictionary, as the keys in a dictionary have to be unique. If you really want the entries in count to be your keys, the best thing I can think of is to make a list of values for each key:

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]]
answer = {}
for c, b in zip(count, bins):
    if c not in answer: answer[c] = []
    answer[c].append(b)
like image 34
inspectorG4dget Avatar answered Nov 13 '22 22:11

inspectorG4dget


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]]'
like image 53
Peter Wood Avatar answered Nov 13 '22 20:11

Peter Wood