我有一本这样的字典:
dict_test ={1: 111, 2: 2222, 3:333, 4:4444, 5:5555, 6:6666,
7: 777, 8: 8888, 9:9999, 10:100010101}
并且想要创建字典的一个子集,例如,使用给定键 8 的前四个值。因此,生成的预期字典将如下所示:
dict_new ={4:4444, 5:5555, 6:6666, 7: 777, 8: 8888}
我试着在下面写一个更通用的函数,在那里我可以更一般地确定我应该回顾多少个以前的值。
def get_x_prev_entries(dictionary: dict, key: str, prev: int):
if key in dictionary:
token = object()
keys = [token]*(prev*-1) + sorted(dictionary) + [token]*diff
print('keys' + str(keys))
new_dict = []
newkeys = []
new_prev= prev
# extract all keys that are between 0 and the specified difference
while new_prev is not 0:
new_prev -= 1
if len(newkeys) == 0:
newkeys= newkeys
else:
newkeys = newkeys.append(keys[keys.index(key)-new_diff])
print(newkeys)
print(new_diff)
new_dict = {k:v for k, v in dictionary.items() if k in newkeys}
return new_dict
else:
print('Key not found')
所以要创建我想要的字典,我最好输入
get_x_prev_entries(dict_test, 8, 4)
但此时我只返回了一个空字典。任何意见,将不胜感激。谢谢!
饮歌长啸
相关分类