Home > Enterprise >  Extracting elements using list of dictionaries in python
Extracting elements using list of dictionaries in python

Time:10-03

I'm currently working on a project where I have a list of dictionaries where i want to apply some functions. Let's say I have this list of dictionaries:

l1 = [{"year":"<year>", "df":"<df1>"}, {"system":"<system>","df":"<df2>"}, {"year":"<year>","month":"<month>","system":"<system>","df":"<df3>"}]

What I want to do is to extract is the element df from each dictionary so my output would be:

l2 = [{year:<year>}, {system:<system>}, {year:<year>,month:<month>,system:<system>}]

How can I do it?

CodePudding user response:

This can be done using the dict.pop() method.

l1 = [{"year":"<year>", "df":"<df1>"}, {"system":"<system>","df":"<df2>"}, {"year":"<year>","month":"<month>","system":"<system>","df":"<df3>"}]

for item in l1:
    item.pop('df')

print(l1)

Note that this deletes the dt fields from the dictionaries.

CodePudding user response:

Assuming you want to do this without modifying l1, you can use a dict comprehension to make a new dict without the key in question:

{k:v for k,v in d.items() if k != 'df'}

Do this for each item in that list with a list comprehension:

l1 = [{"year":"<year>", "df":"<df1>"}, {"system":"<system>","df":"<df2>"}, {"year":"<year>","month":"<month>","system":"<system>","df":"<df3>"}]

# for each dict(d) in l1, make a new dict of all k/v pairs except 'df'
l2 = [{k:v for k,v in d.items() if k != 'df'} for d in l1]

print(l2)
# [{'year': '<year>'}, {'system': '<system>'}, {'year': '<year>', 'month': '<month>', 'system': '<system>'}]

CodePudding user response:

You could use the pop method to remove keys in-place over the items of the list but if you want to preserve the original dictionaries in the list, you will need to make copies to form the new list:

l1 = [{"year":"<year>", "df":"<df1>"}, 
      {"system":"<system>","df":"<df2>"}, 
      {"year":"<year>","month":"<month>","system":"<system>","df":"<df3>"}]

l2 = [d for d in map(dict.copy,l1) if [d.pop('df')]]

print(l2)
[{'year': '<year>'}, 
 {'system': '<system>'}, 
 {'year': '<year>', 'month': '<month>', 'system': '<system>'}]
  • Related