Reputation:
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']}
Upvotes: 1
Views: 85
Reputation: 718
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
Upvotes: 0
Reputation: 5745
Here nice list comprehension in action:
list_dicts = [dict(list(i.items())[:-1]) for i in list_dicts]
Upvotes: 0
Reputation: 1496
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]
Upvotes: 1
Reputation: 734
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
Upvotes: 0