son 3 ❮ Lesson List ❮ Top Page
❯ 3.4 Looping in Dictionaries
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 8m 38s
☷ Interactive readings 5m
To get all the keys, values, or all items, you can use the following methods:
keys()
returns a list of all the keys in the dictionary.
values()
returns a list of all the values in the dictionary.
items()
returns each item in a dictionary as tuples in a list.
While dictionary cannot be used directly in a for loop, it is possible to loop through it keys and values of a dictionary using keys() and values().
To get both keys and values at the same time, you can use items() for iterating.
To form a dictionary from two tuples/lists, you can start by making an empty dictionary first then add the items in a for loop using a simple index assignment or update().
Just like list comprehension, you can make dictionary comprehensions. You group the expression using curly braces instead of square braces.
There are four collection data types in the Python programming language:
List: has order, can be changed, duplicate member OK.
Tuple: has order, can't be changed, duplicate member OK.
Set: has no order, can be change, no duplicate member.
Dictionary: has order, can be change, no duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.