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

我有一本这样的字典:


 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)

但此时我只返回了一个空字典。任何意见,将不胜感激。谢谢!


偶然的你
浏览 147回答 1
1回答

饮歌长啸

使用订单字典from collections import OrderedDict as oddict_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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python