I have:
dictionary = {"foo":12, "bar":2, "jim":4, "bob": 17}
I want to iterate over this dictionary, but over the values instead of the keys, so I can use the values in another function.
For example, I want to test which dictionary values are greater than 6, and then store their keys in a list. My code looks like this:
list = []
for c in dictionary:
if c > 6:
list.append(dictionary[c])
print list
and then, in a perfect world, list would feature all the keys whose value is greater than 6.
However, my for loop is only iterating over the keys; I would like to change that to the values!
Any help is greatly appreciated.
thank you
I’d like to just update this answer to also showcase the solution by @glarrain which I find myself tending to use nowadays.
This is completely cross compatible and doesn’t require a confusing change from
.iteritems(.iteritemsavoids saving a list to memory on Python 2 which is fixed in Python 3) to.items.@Prof.Falken mentioned a solution to this problem
which effectively fixes the cross compatibility issues BUT requires you to download the package
sixHowever I would not fully agree with @glarrain that this solution is more readable, that is up for debate and maybe just a personal preference even though Python is supposed to have only 1 way to do it. In my opinion it depends on the situation (eg. you may have a long dictionary name you don’t want to type twice or you want to give the values a more readable name or some other reason)
Some interesting timings:
In Python 2, the 2nd solution is faster, in Python 3 they are almost exactly equal in raw speed.
However these are only tests for small dictionaries, in huge dictionaries I’m pretty sure that not having a dictionary key lookup (
d[k]) would make.itemsmuch faster.And this seems to be the case