MST

星途 面试题库

面试题:Python中字典(dictionary)有哪些实用的内置方法及使用场景

请详细说明Python字典的items()、keys()、values()、get()、pop()等方法的作用及适用场景,并通过代码示例展示如何使用这些方法解决实际问题,例如统计一段文本中每个单词出现的次数并存储在字典中,然后根据需求获取相关信息。
16.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

items()方法

  1. 作用:返回一个包含字典所有键值对的视图对象。这个视图对象会动态反映字典的变化。
  2. 适用场景:当需要同时获取字典的键和值,进行遍历操作时非常有用,例如同时打印键和值,或者对键值对进行整体处理。
  3. 代码示例
my_dict = {'a': 1, 'b': 2}
for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

keys()方法

  1. 作用:返回一个包含字典所有键的视图对象。该视图对象同样会动态反映字典的变化。
  2. 适用场景:当只需要获取字典中的所有键,进行键的遍历、判断某个键是否存在等操作时使用。
  3. 代码示例
my_dict = {'a': 1, 'b': 2}
keys = my_dict.keys()
print(keys)
if 'a' in keys:
    print("Key 'a' exists.")

values()方法

  1. 作用:返回一个包含字典所有值的视图对象。这个视图对象也会动态反映字典的变化。
  2. 适用场景:当只关心字典中的值,需要对值进行遍历、统计值的总和等操作时适用。
  3. 代码示例
my_dict = {'a': 1, 'b': 2}
values = my_dict.values()
print(values)
total = sum(values)
print(f"Sum of values: {total}")

get()方法

  1. 作用:根据指定的键获取对应的值。如果键不存在,返回指定的默认值(默认为None),而不会像直接通过键访问那样抛出KeyError
  2. 适用场景:当不确定字典中是否存在某个键,又不想因为键不存在而导致程序出错时使用。
  3. 代码示例
my_dict = {'a': 1, 'b': 2}
value = my_dict.get('c', 0)
print(f"Value for key 'c': {value}")

pop()方法

  1. 作用:删除字典中指定键的键值对,并返回被删除的值。如果指定的键不存在,且未提供默认值,则抛出KeyError
  2. 适用场景:当需要删除字典中的某个键值对,并同时获取被删除的值时使用,例如在实现一个缓存,当缓存满时删除某个键值对并返回其值。
  3. 代码示例
my_dict = {'a': 1, 'b': 2}
removed_value = my_dict.pop('b')
print(f"Removed value: {removed_value}")
print(f"Updated dictionary: {my_dict}")

实际问题解决:统计文本中单词出现次数

text = "this is a test this is another test"
word_count = {}
words = text.split()
for word in words:
    word_count[word] = word_count.get(word, 0) + 1

print("Word count dictionary:", word_count)

# 使用items()遍历并打印结果
print("Word - Count pairs:")
for word, count in word_count.items():
    print(f"{word}: {count}")

# 使用keys()判断某个单词是否在统计范围内
if 'test' in word_count.keys():
    print("'test' is in the text.")

# 使用values()统计单词出现的总次数
total_count = sum(word_count.values())
print(f"Total number of words in the text: {total_count}")

# 使用pop()删除某个单词的统计并获取其出现次数
removed_count = word_count.pop('is', 0)
print(f"Removed 'is' with count: {removed_count}")
print(f"Updated word count dictionary: {word_count}")