How to filter dictionary keys based on its corresponding values

前端 未结 6 1144
南笙
南笙 2021-01-30 04:50

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

6条回答
  •  情深已故
    2021-01-30 05:48

    It depends if you would like to modify the dictionary (add or remove items) or not. If not then you could try:

    for value in dictionary.itervalues():  #this returns a generator
         print "do something with the value"
    

    Alternatively if you modify the dictionary you should iterate over a copy of values:

    for value in dictionary.values():  #this returns a list of values
         print "do something with the value"
    

    If you would like both keys and values you can iterate over pairs using dictionary.iteritems() or dictionary.items()

提交回复
热议问题