python dictionary comprehension get sub dictionary where values are greater then 2

StackOverflow https://stackoverflow.com/questions/23451081

  •  15-07-2023
  •  | 
  •  

سؤال

so I have a dictionary called self.outliers that will look like this

{
"foo" : {"freq" : 7, "ids" : [1,2,3,4,5,6,7]},
"bar" : {"freq" : 2, "ids" : [8,9]}
}

I'm trying to pull out all key values that have a frequency > then 2 I've tried:

{(k, self.outliers.get(k)) for k in self.outliers if self.outliers[k]['freq'] > 1}

could anyone help me fix this please as I've been banging my head against this for a while.

هل كانت مفيدة؟

المحلول

You have your syntax mixed up; drop the parentheses and add a colon:

{k: self.outliers[k] for k in self.outliers if self.outliers[k]['freq'] > 2}

This also tests for a frequency over 2 and not 1.

You could just loop over the items:

{k: v for k, v in self.outliers.items() if v['freq'] > 2}

Demo:

>>> outliers = {"foo" : {"freq" : 7, "ids" : [1,2,3,4,5,6,7]},
...             "bar" : {"freq" : 2, "ids" : [8,9]}}
>>> {k: v for k, v in outliers.items() if v['freq'] > 2})
{'foo': {'freq': 7, 'ids': [1, 2, 3, 4, 5, 6, 7]}}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top