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

日本語  ❯

Lesson 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   7m 19s
☷  Interactive readings   5m

Making a Dictionary

Dictionaries are used to store data values in key : value pairs. They are written with curly brackes { } and have keys and values, separated by colon :.

Accessing Dictionary Items

To access the items of a dictionary, you can refer to its key name, inside square brackets.

get(key)
can also access the items by referring to key.

Changing & Adding Values in Dictionary

Generally, keys cannot be changed. You can change the values of a specific item by referring to its key name.

update(dict)
can also update the dictionary. The argument must be a dictionary.

Those two methods can also be used to add new keys:values pair into a dictionary.

Removing Dictionary Items

Similar to the list, 

pop()
removes the element with the specified key. The value of the removed item is the return value of the pop() method

WRITE BETTER CODE
Writing Lengthy Dictionaries Neatly

In comparison to lists and tuples, dictionaries can get very lengthy. Writing them neatly helps with readability.

The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character or the last line of list/dictionary (see example).

LEARN FROM ERRORS
KeyError when Accessing a Key that is not in a Dictionary

A KeyError is raised when a mapping key is accessed and is not found in the mapping.

You can use .get() to return either the value found at the specified key or a default value. It does not fix the problem but at least the error will not shows.

Change Line 6 using .get() instead of brackets [] to resolve the error in the code.

©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