我有一本这样的字典:
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)
但是这时我只得到一个空字典。任何意见,将不胜感激。谢谢!
答案 0 :(得分:0)
使用命令字典
from collections import OrderedDict as od
dict_test ={1: 111, 2: 2222, 3:333, 4:4444, 5:5555, 6:6666, 7: 777, 8: 8888, 9:9999, 10:100010101}
od_dict = od(dict_test)
def get_previous_keys(od_dict, prev=4, given=8):
if given not in od_dict:
return
k, v = [], []
for i in range(given-prev, given):
k.append(i)
v.append(od_dict[i])
return dict(zip(k,v))
print(get_previous_keys(od_dict))
{4: 4444, 5: 5555, 6: 6666, 7: 777}