为了账号安全,请及时绑定邮箱和手机立即绑定

从字典中给定一个键,提取 x 个先前的键值对

从字典中给定一个键,提取 x 个先前的键值对

偶然的你 2022-01-05 10:11:25
我有一本这样的字典: 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)但此时我只返回了一个空字典。任何意见,将不胜感激。谢谢!
查看完整描述

1 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

使用订单字典


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}


查看完整回答
反对 回复 2022-01-05
  • 1 回答
  • 0 关注
  • 146 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信