创建具有两个值的字典时遗漏的值

Missed values when creating a dictionary with two values

我有两个列表如下。

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]]

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

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

它给了我 {"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]}

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

{"0": [3.0, 4.0],"0": [4.0, 5.0]} 不是有效的字典,因为字典中的键必须是唯一的。如果您真的希望 count 中的条目成为您的键,我能想到的最好的办法是为每个键创建一个 list 值:

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)

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

您可以将 list 转换为 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}

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

>>> {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}'

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

>>> 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]]'