Getting All Elements from a Python Dictionary: Usage of keys(), values(), items(), and List Conversion

When you want to access all data stored in a Python dictionary (dict), you might need a list of just the keys, want to aggregate just the values, or process keys and values as a set. Python provides three standard methods for these purposes: keys(), values(), and items().

This article explains how to use each method and how to convert the retrieved data into a list.


目次

1. Getting All Keys: .keys()

Use the .keys() method to get a list of “keys” contained in the dictionary.

# Dictionary of subjects and scores
exam_scores = {
    "Math": 85,
    "Science": 92,
    "English": 78
}

# Get all keys
subjects = exam_scores.keys()

print(f"Keys: {subjects}")
print(f"Type: {type(subjects)}")

# Iterate through keys with a for loop
print("--- Subject List ---")
for subject in subjects:
    print(subject)

Output:

Keys: dict_keys(['Math', 'Science', 'English'])
Type: <class 'dict_keys'>
--- Subject List ---
Math
Science
English

The return value is a special object called dict_keys, but it can be used directly in a for loop.


2. Getting All Values: .values()

Use the .values() method to get a list of “values” contained in the dictionary. This is convenient when you want to calculate the sum or average of values.

# Get all values
scores = exam_scores.values()

print(f"Values: {scores}")
print(f"Type: {type(scores)}")

# Calculate the sum (sum function is available)
total_score = sum(scores)
print(f"Total Score: {total_score}")

Output:

Values: dict_values([85, 92, 78])
Type: <class 'dict_values'>
Total Score: 255

3. Getting Key-Value Pairs: .items()

Use the .items() method to get keys and values together. Each element retrieved is a tuple in the format (key, value). This is often used in combination with a for loop to expand (unpack) keys and values into variables simultaneously.

# Get all pairs
pairs = exam_scores.items()

print(f"Pairs: {pairs}")
print(f"Type: {type(pairs)}")

# Extract key and value simultaneously in a for loop
print("--- Score Details ---")
for subject, score in pairs:
    print(f"{subject}: {score} points")

Output:

Pairs: dict_items([('Math', 85), ('Science', 92), ('English', 78)])
Type: <class 'dict_items'>
--- Score Details ---
Math: 85 points
Science: 92 points
English: 78 points

4. Converting to List Format (list())

As mentioned above, these methods return “View Objects” (dict_keys, dict_values, dict_items). While they look like lists, you cannot access them using an index (like [0]). If you want to access elements using an index, you must explicitly convert them to the list type using the list() function.

# Convert view objects to lists
subject_list = list(exam_scores.keys())
score_list = list(exam_scores.values())
pair_list = list(exam_scores.items())

print(f"Key List: {subject_list}")
print(f"1st Subject: {subject_list[0]}")  # Index access is possible because it is a list

print(f"Value List: {score_list}")
print(f"Pair List: {pair_list}")

Output:

Key List: ['Math', 'Science', 'English']
1st Subject: Math
Value List: [85, 92, 78]
Pair List: [('Math', 85), ('Science', 92), ('English', 78)]

Summary

Here is how to retrieve elements from a dictionary:

  • .keys(): Get a list of keys.
  • .values(): Get a list of values.
  • .items(): Get a list of (key, value) pairs.

The retrieved data are view objects. If you need to perform index operations, convert them to lists using list().

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次