Python:按键(元组)将字典拆分为较小的字典

我有一个字典,其中键是两个整数的元组,(x,y)值是字符串。

如何将这本字典拆分成更小的字典,其中拆分取决于y-value 是否大于某个阈值?

例如,假设我有键(字典值无关紧要,所以我在这里省略了它们)

(0, 2), (0, 4), (0, 10), (0, 3), (0, 11), (0, 20), (0, 8), (0, 14)

并说我有门槛0, 5, 10, 15

然后,一个拆分应包含一个具有以下键的字典:

(0,2), (0,4), (0,3)

因为 y 值都大于 0,但不大于 5。

那么下一个字典应该有键

(0,8)

因为它大于 0 和 5,但不大于 10。

然后我们有 (0, 10), (0, 11), (0, 14)

因为它大于(或等于)0、5、10,但不是 15。

最后,我们(0, 20)自己。


尚方宝剑之说
浏览 292回答 3
3回答

白猪掌柜的

您可以使用collections.defaultdict、迭代和更新由存储桶边界确定的键。这比创建可变数量的变量更好。d = {(0, 2): 1, (0, 4): 2, (0, 10): 3, (0, 3): 4,&nbsp; &nbsp; &nbsp;(0, 11): 5, (0, 20): 6, (0, 8): 7, (0, 14): 8}L = [0, 5, 10, 15, float('inf')]&nbsp; # include infinite to facilitate later comparisonsfrom collections import defaultdictdd = defaultdict(dict)for k, v in d.items():&nbsp; &nbsp; for i, j in zip(L, L[1:]):&nbsp; &nbsp; &nbsp; &nbsp; if i <= k[1] < j:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dd[i].update({k: v})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; breakprint(dd)defaultdict(dict,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {0: {(0, 2): 1, (0, 3): 4, (0, 4): 2},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;5: {(0, 8): 7},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;10: {(0, 10): 3, (0, 11): 5, (0, 14): 8},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;15: {(0, 20): 6}})该算法可以通过使用bisect而不是L按顺序迭代边界来改进。

潇潇雨雨

当然这可以写得更好,但你应该明白这个想法。只需遍历 dict,并根据您可以动态定义或生成的各种条件检查键的 y 值。thing = {&nbsp; &nbsp; (1,2): 'a',&nbsp; &nbsp; (2,19): 'b'}d1 = {}d2 = {}for k, v in thing.items():&nbsp; &nbsp; // while iterating through the original dict, write some logic to determine how you want to split up based on the y values.&nbsp; &nbsp; if k[1] < 5:&nbsp; &nbsp; &nbsp; &nbsp; d1[k] = v&nbsp; &nbsp; if k[1] < 10:&nbsp; &nbsp; &nbsp; &nbsp; d2[k] = vprint(d1, d2)

梦里花落0921

这应该有效。original_dict = {(0, 2):"a", (0, 4):"b", (0, 10):"c",&nbsp;(0, 3):"d", (0, 11):"e", (0, 20):"f", (0, 8):"g", (0, 14):"h"}thresholds = [0, 5, 10, 15]thresholds = sorted(thresholds,reverse=True)new_dict_of_dicts = {} #threshold: dictfor threshold in thresholds:&nbsp; &nbsp; new_dict_of_dicts[threshold] = {}&nbsp; &nbsp; for key in list(original_dict.keys()):&nbsp; &nbsp; &nbsp; &nbsp; if key[1] > threshold:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new_dict_of_dicts[threshold][key] = original_dict.pop(key)print(new_dict_of_dicts)&nbsp;#{15: {(0, 20): 'f'}, 10: {(0, 11): 'e', (0, 14): 'h'}, 5: {(0, 10): 'c', (0, 8): 'g'}, 0: {(0, 2): 'a', (0, 4): 'b', (0, 3): 'd'}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python