There is a dictionary with data:

active_object.data.groups['foo'] active_object.data.groups['bar'] ... active_object.data.groups['ets'] 

I iterate over all its elements in a loop:

 for object in active_object.data.groups: 

And I need to get the key 'foo','bar'...'ets' (not a sequence number) in order to find the corresponding element in a different dictionary (associative array). What is the most appropriate way to do this? Essentially, I need a PHP foreach($array as $key=>$value) equivalent foreach($array as $key=>$value)

  • Unlike php in python, it is customary to distinguish between lists (an indexed array) and dictionaries (an associative array). Your code already enumerates all possible keys in the dictionary: for key in some_dict Related question: How to get all values ​​by key from an array Mention in the question header for clarity what you want: indices (whole numbers) from a list or keys (any hashable object) from the dictionary. - jfs
  • I basically found a solution for key, object in active_object.data.groups.items(): this is what I needed - Crantisz
  • one
    What “usually” happens is not important, we are talking about your specific question. Edit the text of the question and indicate that you want both the key and the value. Because if you need only a key, then items() is the wrong answer: this method does not return keys, it returns key / value pairs. And the correct answer would be: for key in active_object.data.groups: (note that if groups is a dictionary, then it is the keys that are returned, not the values). It doesn't matter if the question has the wrong terminology, if the answers say exactly which terminology is correct. - jfs
  • one
    “Dictionary” is the name for the “associative array” in Python. Run the python command so that the REPL appears (you can online) and play around with the dictionary: d = dict(a=1,b=2,c=3) See what they return: list(d) , list (d.keys ()) , list(d.values()) , list(d.items()) . Decide what you want in your case and update the question accordingly. Look in the dictionary for the meaning of words: dictionary, keys, values, items. Both keys and dictionary values ​​are objects in Python. - jfs
  • one
    searching by class name says that this is some kind of specialized collection, not a list or dictionary. And if list(d) is list(d.values()) and not list(d.keys()) , then it does not behave like a dictionary (for which it is always: list(d)==list(d.keys()) ). In this case, it is better to explicitly indicate the groups type with reference to the documentation (knowledge of the behavior of lists, dictionaries in Python will not help in this case). By the way, if you ever create your own classes for collections, then try to follow the Sequence or Mapping protocol if possible. - jfs

1 answer 1

You can get key pairs, values ​​from the dictionary using items() :

 for key, object in active_object.data.groups.items():