With list comprehensions:
myDict = [{'first': 'James', 'middle': 'Smith', 'last': 'Joule'},
{'first': 'James', 'middle': 'Johnson', 'last': 'Watt'},
{'first': 'Christian', 'middle': 'Edward', 'last': 'Doppler'},
{'first': 'Robert', 'last': 'Antonio'}]
keys = {"middle", "last"}
l = [{k:v for k, v in i.items() if k in keys} for i in myDict]
But you can also use map for this:
myDict = [{'first': 'James', 'middle': 'Smith', 'last': 'Joule'},
{'first': 'James', 'middle': 'Johnson', 'last': 'Watt'},
{'first': 'Christian', 'middle': 'Edward', 'last': 'Doppler'},
{'first': 'Robert', 'last': 'Antonio'}]
keys = {"middle", "last"}
l = list(map(lambda x: {k:v for k, v in x.items() if k in keys}, myDict))
print(l)
output:
[{'last': 'Joule', 'middle': 'Smith'}, {'last': 'Watt', 'middle': 'Johnson'}, {'last': 'Doppler', 'middle': 'Edward'}, {'last': 'Antonio'}]
Answer from neverwalkaloner on Stack OverflowWith list comprehensions:
myDict = [{'first': 'James', 'middle': 'Smith', 'last': 'Joule'},
{'first': 'James', 'middle': 'Johnson', 'last': 'Watt'},
{'first': 'Christian', 'middle': 'Edward', 'last': 'Doppler'},
{'first': 'Robert', 'last': 'Antonio'}]
keys = {"middle", "last"}
l = [{k:v for k, v in i.items() if k in keys} for i in myDict]
But you can also use map for this:
myDict = [{'first': 'James', 'middle': 'Smith', 'last': 'Joule'},
{'first': 'James', 'middle': 'Johnson', 'last': 'Watt'},
{'first': 'Christian', 'middle': 'Edward', 'last': 'Doppler'},
{'first': 'Robert', 'last': 'Antonio'}]
keys = {"middle", "last"}
l = list(map(lambda x: {k:v for k, v in x.items() if k in keys}, myDict))
print(l)
output:
[{'last': 'Joule', 'middle': 'Smith'}, {'last': 'Watt', 'middle': 'Johnson'}, {'last': 'Doppler', 'middle': 'Edward'}, {'last': 'Antonio'}]
Use neverwalkaloner's answer if you are just doing this once. But, if you find yourself manipulating lists of dictionaries often, I've written a free library called PLOD that streamlines much of this.
>>> from PLOD import PLOD
>>> l = PLOD(myDict).dropKey("middle").returnList()
>>> l
[{'last': 'Joule', 'first': 'James'}, {'last': 'Watt', 'first': 'James'}, {'last': 'Doppler', 'first': 'Christian'}, {'last': 'Antonio', 'first': 'Robert'}]
>>> print(PLOD(l).returnString())
[
{first: 'James' , last: 'Joule' },
{first: 'James' , last: 'Watt' },
{first: 'Christian', last: 'Doppler'},
{first: 'Robert' , last: 'Antonio'}
]
>>>
The library is on PyPi: https://pypi.python.org/pypi/PLOD
To more universally do what you want, I'd need to add a new class method. Perhaps .filterKeys. Perhaps I'll do that in version 1.8. It would then go:
>>> l = PLOD(myDict).filterKeys(['first', 'last']).returnList()
Hmmm...
BTW, the lib supports Python 2.7.x right now. Still working on the 3.5.x release.
python - Filter a dictionary using one of multiple keys - Stack Overflow
Python - Filter dictionary with multiple keys - Stack Overflow
python - Filter dict to contain only certain keys? - Stack Overflow
python - Filtering a list of dictionaries based on multiple values - Stack Overflow
Videos
Check if first value of the tuple key is 2, with dict comprehension:
{k: v for k, v in dct.items() if k[0]==2}
So:
In [11]: dct = {(0, 'DRYER'): [103.0, 131.0, 9.0, 1.24],
...: (2, 'DRYER'): [106.0, 120.0, 5.0, 1.24],
...: (2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]}
...:
In [12]: {k: v for k, v in dct.items() if k[0]==2}
Out[12]:
{(2, 'DRYER'): [106.0, 120.0, 5.0, 1.24],
(2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]}
Try using filter
new_dict = dict(filter(function(), old_dict.items()))
in your case function() would be
lambda it: True if it[0][0] == 2 else False
Basically filter() grabs a function and an iterable and removes all the elements from iterable, if the function returns False
Constructing a new dict:
dict_you_want = {key: old_dict[key] for key in your_keys}
Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.
Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.
Removing everything in-place:
unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
Slightly more elegant dict comprehension:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}
If you first sort your list by "name", you can use itertools.groupby to group them, then use min with a lambda to find the minimum "price" in each group.
>>> from itertools import groupby
>>> sorted_orders = sorted(orders, key=lambda i: i["name"])
>>> [min(g, key=lambda j: j["price"]) for k,g in groupby(sorted_orders , key=lambda i: i["name"])]
[{'name': 'v', 'price': 123, 'location': 'Mars'},
{'name': 'x', 'price': 124, 'location': 'Mars'},
{'name': 'y', 'price': 456, 'location': 'Mars'},
{'name': 'z', 'price': 123, 'location': 'Mars'}]
You can use itertools.groupby:
from itertools import groupby
print(
[
min(g[1], key=lambda x: x['price'])
for g in groupby(sorted(orders, key=lambda o: o['name']), lambda o: o['name'])
]
)
Output:
[
{'name': 'v', 'price': 123, 'location': 'Mars'},
{'name': 'x', 'price': 124, 'location': 'Mars'},
{'name': 'y', 'price': 456, 'location': 'Mars'},
{'name': 'z', 'price': 123, 'location': 'Mars'}
]