创建具有两个值的字典时错过的值

Man*_*mal 6 python dictionary python-itertools

我有两个列表如下.

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]]
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下创建字典;

dictionary = dict(itertools.izip(count, bins))
Run Code Online (Sandbox Code Playgroud)

它给了我 {"0": [7.0, 8.0], "1": [10.0, 11.0], "2": [11.0, 12.0]}

它只提供唯一的键值,但我需要得到所有的对,如下所示.

{"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]}
Run Code Online (Sandbox Code Playgroud)

或者上面词典中的键和值的交换是可以接受的.(因为键应该是唯一的)我该怎么做?

Pet*_*ood 3

您不能使用 alist作为字典的键,因为它是可变的。

您可以将 转换listtuple

>>> 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}
Run Code Online (Sandbox Code Playgroud)

如果要序列化为json,则键必须是字符串。您可以将 bin 转换为字符串:

>>> {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}'
Run Code Online (Sandbox Code Playgroud)

或者,只需序列化这些对,并在接收端创建字典:

>>> 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]]'
Run Code Online (Sandbox Code Playgroud)