Python 如何在没有最后一项的情况下从字典中提取元素 我需要在没有最后一个元素的情况下重新实例化字典

Python 如何在没有最后一项的情况下从字典中提取元素 我需要在没有最后一个元素的情况下重新实例化字典,python,dictionary,Python,Dictionary,下面是示例列表和字典 [{'emptype': ['Manager'], 'Designation': ['Developer']}] {'emptype': ['Manager'], 'Designation': ['Developer']} 词典目录 [{'emptype': ['Manager'], 'Designation': ['Developer'], 'projecttype': ['temp']}] {'emptype': ['Manager'],

下面是示例列表和字典

[{'emptype': ['Manager'],
  'Designation': ['Developer']}]
 {'emptype': ['Manager'],
      'Designation': ['Developer']}
词典目录

[{'emptype': ['Manager'],
  'Designation': ['Developer'],
  'projecttype': ['temp']}]
{'emptype': ['Manager'],
  'Designation': ['Developer'],
  'projecttype': ['temp']}
字典

[{'emptype': ['Manager'],
  'Designation': ['Developer'],
  'projecttype': ['temp']}]
{'emptype': ['Manager'],
  'Designation': ['Developer'],
  'projecttype': ['temp']}
如何提取除last之外的元素

应从字典列表中删除

[{'emptype': ['Manager'],
  'Designation': ['Developer']}]
 {'emptype': ['Manager'],
      'Designation': ['Developer']}
期望从字典中删除

[{'emptype': ['Manager'],
  'Designation': ['Developer']}]
 {'emptype': ['Manager'],
      'Designation': ['Developer']}

下面是一份正在实施的清单:

  list_dicts = [dict(list(i.items())[:-1]) for i in list_dicts]

删除字典最后一个元素的基本操作是
mydict
(list(mydict)[-1])。如果您有一个字典列表,您可以循环使用它们,并将该函数应用于每个字典

mydict.keys()[-1]使用map应用于python2

d = [{'emptype': ['Manager1'],
  'Designation': ['Developer1'],
  'projecttype': ['temp1']},
   {'emptype': ['Manager2'],
  'Designation': ['Developer2'],
  'projecttype': ['temp2']},
  {'emptype': ['Manager3'],
  'Designation': ['Developer3'],
  'projecttype': ['temp3']},
  {'emptype': ['Manager4'],
  'Designation': ['Developer4'],
  'projecttype': ['temp4']}]

def remove_last_key(item: dict):
    item.pop(
        list(item.keys())[-1]
    )
    return item

list(map(remove_last_key,d))
这是在Python3.7.7上测试的(应该可以在3.6+上使用)-根据顺序使用dict时,Python版本很重要。您可以在此处阅读更多内容:

编辑:

在某些情况下,列表理解可能在性能方面提供一些优势,一些人认为列表理解更清晰。在这种情况下:

[remove_last_key(item) for item in d]

建议你只在有序字典里做。。。python内置的dict不一定是有序的,所以你不能期望任何键值对始终保持最后或第一,但我使用的是python 3.8,所以它现在很流行,不需要orderdictOk所以它不重要TypeError:“dict_keys”对象不是Subscribptable您是否使用python3?是的python3.8版本TypeError:“dict_items”对象不是Subscribptable我们需要确切地看到您的列表是什么样子,因为它没有任何意义…以这个为例
[{'emptype':['Manager'],'Designation':['Developer'],'projecttype':['temp']}]
我编辑了它,也许现在可以试试。。。问题是我没有指定要列出的项目…是否必须编写函数,我们是否可以不使用函数编写,您的代码运行良好回答很好。。演示得很好。@Maws您仍然可以使用我向您展示的一行程序…我个人发现使用函数可以提高可读性,但它不是强制性的,正如@adirabargil的回答所示。