Assuming a list of dicts:
[{'a':3434,'b':23424,'c':3231,'d':24334243},
{'a':344,'b':234,'c':321,'d':24334}
{'a':34,'b':2424,'c':31,'d':2434243},...]
Is there a one-liner way to filter the list getting the dictionaries only with certain keys ['a','b']?
for instance:
Result = [{'a':3434,'b':23424},
{'a':344,'b':234}
{'a':34,'b':2424},...]
Note: my current solution is with for loops, totally un-elegant
This would be my homemade approach.
newLst = [{k:v for k,v in dicts.items() if k in ['a','b']}for dicts in last]
a = [{'a':3434,'b':23424,'c':3231,'d':24334243},{'a':344,'b':234,'c':321,'d':24334},{'a':34,'b':2424,'c':31,'d':2434243}]
r = []
for i in a:
if ('a' in i) and ('b' in i):
r.append({'a':i['a'], 'b':i['b']})
print(r)
output
[{'a': 3434, 'b': 23424}, {'a': 344, 'b': 234}, {'a': 34, 'b': 2424}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.