Py学习  »  rajendra  »  全部回复
回复总数  1
5 年前
回复了 rajendra 创建的主题 » python:按键(元组)将字典拆分为更小的字典

这应该管用。

original_dict = {(0, 2):"a", (0, 4):"b", (0, 10):"c",
 (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: dict
for threshold in thresholds:
    new_dict_of_dicts[threshold] = {}
    for key in list(original_dict.keys()):
        if key[1] > threshold:
            new_dict_of_dicts[threshold][key] = original_dict.pop(key)

print(new_dict_of_dicts) 
#{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'}}