You can use a dict comprehension:
{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
And in Python 2, starting from 2.7:
{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}
Answer from Thomas on Stack OverflowYou can use a dict comprehension:
{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
And in Python 2, starting from 2.7:
{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}
dict((k, v) for k, v in points.items() if all(x < 5 for x in v))
You could choose to call .iteritems() instead of .items() if you're in Python 2 and points may have a lot of entries.
all(x < 5 for x in v) may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an and) but it will work fine;-).
How to filter through a dictionary returning a list of key objects?
filter items in a python dictionary where keys contain a specific string - Stack Overflow
Filtering a dictionary value from a list of dictionary using lambda and filter in python - Stack Overflow
python filter list of dictionaries based on key value - Stack Overflow
Videos
So let's say I have a dictionary of
dict = { chevy_01 : "Ford", chevy_02: "Tahoe"}
I want to filter through the KEYS of the dict and get the last two characters of the keys while later performing another function. So I imagine something like this
{for keys in vals print (key[-2:]}
But I want the end of the function to return a list of the last two characters in the dict so it will just return [01, 02].
I want to do this in a lambda function I'm bad at dict comprehension. Can someone help me out?
How about a dict comprehension:
filtered_dict = {k: v for k, v in d.iteritems() if filter_string in k}
One you see it, it should be self-explanatory, as it reads like English pretty well.
This syntax requires Python 2.7 or greater.
In Python 3, there is only dict.items(), not iteritems() so you would use:
filtered_dict = {k: v for k, v in d.items() if filter_string in k}
You can use the built-in filter function to filter dictionaries, lists, etc. based on specific conditions.
filtered_dict = dict(
filter(lambda item: filter_str in item[0], d.items())
)
The advantage is that you can use it for different data structures.
Seeing your initial code, this should do the same thing
>>> l = [{'abc': 'def'}, {'ghi': 'jul'}, {'Name': 'my-name'}]
>>> [i["Name"] for i in l if "Name" in i][0]
'my-name'
Your code returns only the first occurence.Using my approach, and probably also if you would use filter, you'll get (first) a list of all occurrences than only get the first (if any). This would make it less "efficient" IMHO, so I would probably change your code to be something more like this:
def get_json_val(l, key):
for item in l:
if not key in item: continue
return item[key]
Why are you iterating over your dict? That defeats the purpose. Just do
[d for d in l if key in d]
Or if you feel some compulsion to use lambda and filter:
filter(lambda d: key in d, l)
Note, these return lists instead of the corresponding value. If you want the value, you'll have to index into the list. Simply out, using a loop is probably the most reasonable approach, just don't iterate over your dict:
def f(key, l):
for d in l:
if key in d:
return d[key]
You can try a list comp
>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
Another way is by using filter
>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
Trying a few answers from this post, I tested the performance of each answer.
As my initial guess, the list comprehension is way faster, the filter and list method is second and the pandas is third, by far.
defined variables:
import pandas as pd
exampleSet = [{'type': 'type' + str(number)} for number in range(0, 1_000_000)]
keyValList = ['type21', 'type950000']
1st - list comprehension
%%timeit
expectedResult = [d for d in exampleSet if d['type'] in keyValList]
60.7 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
2nd - filter and list
%%timeit
expectedResult = list(filter(lambda d: d['type'] in keyValList, exampleSet))
94 ms ± 328 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
3rd - pandas
%%timeit
df = pd.DataFrame(exampleSet)
expectedResult = df[df['type'].isin(keyValList)].to_dict('records')
336 ms ± 1.84 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
On a side note, using pandas to deal with a dict is not a great idea since the pandas.DataFrame is basically a more memory consuming dict and if you are not going to use a dataframe in the end it is just inefficient.
d = dict((k, v) for k, v in d.iteritems() if v > 0)
In Python 2.7 and up, there's nicer syntax for this:
d = {k: v for k, v in d.items() if v > 0}
Note that this is not strictly a filter because it does create a new dictionary.
try
y = filter(lambda x:dict[x] > 0.0,dict.keys())
the lambda is feed the keys from the dict, and compares the values in the dict for each key, against the criteria, returning back the acceptable keys.