1
  • I need to re-instantiate the dictionary without last element

Below are sample list and dictionary

List of Dictionary

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

Dictionary

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

How to extract the elements except last

Expected out from list of dictionary

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

Expected out from dictionary

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

4 Answers4

1

Using map:

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))

This was tested on Python 3.7.7 (and should work on 3.6+) - When working on dict based on their order, the Python version matters. You can read more here: Are dictionaries ordered in Python 3.6+?

EDIT:

In certain cases, list comprehension might provide some advantages in terms of performance and are considered clearer by some. In this case:

[remove_last_key(item) for item in d]
arabinelli
  • 1,006
  • 1
  • 8
  • 19
0
def remove_item(data):
    if type(data) is list:
        result = []
        for item in data:
            result.append(remove_item(item))
        return result
    elif type(data) is dict:
        data.pop(list(data.keys())[-1])
        return data
    return data
    
abdulsaboor
  • 678
  • 5
  • 10
0

Here nice list comprehension in action:

  list_dicts = [dict(list(i.items())[:-1]) for i in list_dicts]
adir abargil
  • 5,495
  • 3
  • 19
  • 29
0

The basic operation for removing the last element of a dictionary mydict is mydict.pop(list(mydict)[-1]). If you have a list of dictionaries you can loop over them and apply the function to each dictionary.

mydict.keys()[-1] applies to python2

Marc
  • 712
  • 4
  • 7