Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

son 3    ❮    Lesson List    ❮    Top Page

3.1 Tuples  

3.2 Sets  

3.3 Dictionaries  

❯  3.4  Looping in Dictionaries

3.5 Zip and Enumerate  

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   8m 38s
☷  Interactive readings   5m

Getting All Keys & Values in a Dictionary

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.

Looping through a Dictionary

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.

Composing a Dictionary from Tuples

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().

Making a Dictionary Comprehension

Just like list comprehension, you can make dictionary comprehensions. You group the expression using curly braces instead of square braces.

WRITE BETTER CODE
Choosing the Right Collection

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.

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse