Social Widget

Responsive Ads Here

Tuesday, January 21, 2020

Loop Through Python Dictionaries

Dictionary

     A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.






Using .keys()

one method of iterating over the keys in a dictionary is to use the .keys() method which returns a dict_keys object that is then iterated over as we store each value in our x variable.



Using .values()

If we want to get right at each value in the dictionary, then using the .values() method will store the term’s value in x rather than the key.



Using .items()

More often than not, you will want access to both the key and the value. In this scenario, use the .items() method, which returns each key-value pair as a two-value tuple.

To pre-split the tuple, specify two variables in your for loop so that the first tuple value (the key) and the second (the value) are stored in the first and second variables respectively.



There are many methods available, each with their own pros and cons. Once you get into larger executions you may find performance differences, however, especially at a beginner’s level, try to iterate intentionally over what is necessary.

#python #dictionary #iterations

No comments:

Post a Comment