Missing values ​​when creating a dictionary with two values

I have two lists:

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 the following:

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

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

It gives only unique key values, but I need to get all the pairs as shown 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 the exchange of keys and values ​​in the above dictionary is permissible (since the keys must be unique) How can I do this?

+6
source share
2 answers

You cannot use list as a key to a dictionary, as it is modified.

You can convert list to 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 serialize in json , the keys must be strings. Instead, you can convert cells to strings:

 >>> {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 serialize the pairs and make the dictionary on the receiving side:

 >>> 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]]' 
+3
source

{"0": [3.0, 4.0],"0": [4.0, 5.0]} not a valid dictionary because the keys in the dictionary must be unique. If you really want the entries in count be your keys, the best I can think of is to make a list 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) 
+2
source

All Articles