• 1
    数据输入输出
    • 任务
  • 2
    条件语句
    • 任务
  • 3
    for循环
    • 任务
  • 4
    字符串
    • 任务
  • 5
    while循环
    • 任务
  • 6
    列表
    • 任务
  • 7
    二维数组
    • 任务
  • 8
    字典
    • 任务
  • 9
    集合
    • 任务
  • 10
    函数与递归
    • 任务
  • к

课程 8. Dictionary

难度:

任务«值的合并»

💻 Python
想象一下,你正在旅行,并使用两个不同的词典:一个通用词典,另一个是主题词典,例如“餐厅”。你的任务是将这两个词典合并为一个,以便所有必要的短语都触手可及。如果在两个词典中找到相同的单词,你需要从主题词典中获取翻译(我们认为它更准确)。

输入格式

首先输入通用词典中的短语数量,然后以“单词:翻译”的格式每行输入一个短语。之后,输入主题词典中的短语数量,并以同样的格式“单词:翻译”输入这些短语。

输出格式

程序应推导出合并后的字典,其中每个单词及其翻译由冒号分隔,而"单词:翻译"对由逗号和空格分隔。最终字典中单词的顺序不重要。

示例

输入

3
HELLO: Hello
goodbye: Goodbye
thank you: Thank you
2
HELLO: Hello
Water: Water

输出

HELLO: 你好, goodbye: 再见, thank you: 谢谢, Water: 水

提示

Useful methods for working with dictionaries in Python

Dictionaries are one of the most powerful and flexible data structures in Python. To use them effectively, it is important to know the basic methods. Let's take a closer look at them.

The keys() method

Returns all dictionary keys as a special representation object dict_keys.

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
keys = my_dict.keys()
print(keys)  # Output: dict_keys(['key1', 'key2', 'key3'])

A useful tip: The dict_keys object is iterable, meaning you can use it in a for loop. However, this is not a list. If you need a list of keys (for example, for index access), simply convert it using the list() function.

key_list = list(my_dict.keys())
print(key_list[0]) # Output: key1

The values() method

Returns all dictionary values as a representation object dict_values.

values = my_dict.values()
print(values) # Output: dict_values(['value1', 'value2', 'value3'])

A useful tip: Like dict_keys, dict_values can be iterated, but it is not a list. The conversion to list() also works if you need a list of values. This is convenient, for example, to check for the presence of a value.

The items() method

Returns all key-value pairs as a dict_items object, where each pair is represented as a tuple.

items = my_dict.items()
print(items) # Output: dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

A useful tip: This method is incredibly convenient for iterating through a dictionary when you need both a key and a value at the same time. This is considered the most "Pythonic" way to bypass the dictionary.

for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

get() method

Returns the value by key. If there is no key, it returns the default value (or None if it is not specified).

value = my_dict.get("key1")
print(value) # Output: value1

value_nonexistent = my_dict.get("key4", "there is no such key")
print(value_nonexistent) # Output: there is no such key

A useful tip: Use get() instead of direct access through square brackets (my_dict["key4"]) when you are not sure if the key exists in the dictionary. This will avoid the KeyError error and the crash of the program. This is much safer when working with data that comes from external sources.

The popitem() method

Deletes and returns the last added key-value pair as a tuple.

last_item = my_dict.popitem()
print(last_item) # Output: ('key3', 'value3')
print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2'}

A useful tip: This method works according to the LIFO (Last-In, First-Out) principle. It is useful when you need to process dictionary elements in the reverse order of their addition. (Guaranteed LIFO order is supported in Python 3.7+).

The update() method

Updates the dictionary by adding key-value pairs from another dictionary or from an iterable object with pairs.

# The original my_dict dictionary is already without 'key3'
my_dict.update({"key4": "value4", "key1": "new value1"})
print(my_dict)
# Output: {'key1': 'new value1', 'key2': 'value2', 'key4': 'value4'}

A useful tip: Note that if the key from the updating dictionary already exists in the original one, its value will be overwritten. update() is an effective way to merge two dictionaries.

Nested dictionaries

Dictionaries can contain other dictionaries as values. This allows you to create complex hierarchical data structures very similar to the JSON format.

nested_dict = {
    "key1": {"plugg1": "value1"},
"key2": {"plugg2": "value2"}
}

# Accessing the nested value
print(nested_dict["key1"]["plugg1"]) # Output: value1

An example of a multidimensional structure in dictionaries

students = {
    "Alice": {"age": 25, "grades": [88, 92, 85]},
    "Bob": {"age": 22, "grades": [79, 85, 80]},
    "Charlie": {"age": 23, "grades": [90, 87, 85]}
}

# Getting Alice's age
print(students["Alice"]["age"]) # Output: 25

# Getting the first grade Bob
print(students["Bob"]["grades"][0]) # Output: 79

# Adding a new student
students["David"] = {"age": 24, "grades": [82, 79, 88]}
print(students)

A useful tip: When working with nested dictionaries, the risk of getting a KeyError increases. For secure access to the embedded data, you can use a chain of calls get().

# Safely obtaining the age of a student, which may not be
age = students.get("Eve", {}).get("age", "Unknown")
print(age) # Output: Unknown

Here students.get("Eve", {}) will return an empty dictionary {}, since there is no student "Eve", and already this empty dictionary will be called .get("age", ...), which will prevent the error.

main.py
测试 1
测试 2
测试 3
测试 4
测试 5
测试 6
测试 7
测试 8
测试 9
测试 10
开发者解答

🎉 恭喜! 🎉

你出色地完成了任务!这是一个不小的挑战,但你找到了正确答案。你离编程大师又近了一步!继续保持,每一步都让你更强大。

AD

广告

red-snake blue-snake green-snake

正在运行代码...

AI助手

你好!我是你的编程助手。随时向我提问关于 Python 的问题——我可以解释函数、方法,并帮助你完成当前任务!