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

课程 8. Dictionary

难度:

任务«结论部分»

💻 Python
你在一家小商店担任分析师。你拥有每天购买记录的信息。每笔购买都以字典形式呈现,其中键是商品名称,值是该商品的购买数量。你需要整理出一份总购买清单,并计算每天每种商品售出的总数量。

输入格式

首先输入整数   n   – 当天登记的购买记录数量。
然后输入   n   条购买数据。每条购买记录按以下格式输入:
首先输入整数 m   – 本次购买中不同商品的数量。
然后输入 m 个商品名称(字符串)和该商品的购买数量(整数),之间用空格分隔。

输出格式

提供商品的总列表以及每种产品售出的总数量。每种产品必须单独显示在一行,格式为:  "数量 名称"。产品应按商品名称的字典序进行排序。

示例

输入

2
3
Apple 2
Milk 1
Bread 1
2
Apple 1
Cheese 1

输出

牛奶 1
奶酪 1
面包 1
苹果 3

提示

Dictionaries in python

Dictionaries in Python are a powerful and indispensable data structure that allows you to store information in the form of key-value pairs. Imagine a real dictionary or phone book: knowing a unique word (key), you instantly find its definition (meaning). Dictionaries simplify organization and, most importantly, provide very fast access to data based on unique keys.

The main characteristics of dictionaries

  • The keys are unique: Each key in the dictionary must be unique. Trying to add a key that already exists will simply overwrite its value.
  • Changeability: Dictionaries are mutable objects. You can add, modify, and delete key-value pairs after creating a dictionary.
  • Disorder (historically): In older versions of Python (before 3.7), dictionaries were considered unordered. However, starting with Python 3.7, they preserve the order in which elements are inserted. You should be careful to rely on this order if your code is supposed to run on older versions.

A useful tip: Only immutable data types such as strings, numbers, or tuples can be used as keys. Lists or other dictionaries cannot be keys, as they can be changed. But you can use absolutely any data type as values: numbers, strings, lists, and even other dictionaries.

Ways to create dictionaries

Dictionaries can be created in several ways:

1. Empty dictionary

my_dict = {}
# or using the built-in function
my_dict = dict()

2. Dictionary with elements (literal method) This is the most common and readable way.

user_profile = {
"username": "alex",
"level": 15,
"items": ["sword", "shield", "potion"]
}

3. Using the dict function with named arguments This method is convenient for simple dictionaries where the keys are strings.

my_dict = dict(key1="value1", key2="value2")

4. Creating tuples (pairs) from a list This method is useful when the data is received as a list of pairs.

pairs = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(pairs)
# Result: {'a': 1, 'b': 2, 'c': 3}

Access to the elements

Dictionary values are accessed through their keys in square brackets.

my_dict = {"key1": "value1", "key2": "value2"}
print(my_dict["key1"]) # Output: value1

An important point: If you try to access a key that does not exist, Python will cause a KeyError error. To avoid this, use the .get() method.

Secure access using the .get() method The .get() method returns None if the key is not found and does not cause an error. You can also pass the second argument the default value, which will be returned instead of None.

print(my_dict.get("key3")) # Output: None
print(my_dict.get("key3", "not found")) # Conclusion: not found

Changing and adding elements

Adding or changing elements is very simple:

my_dict = {"key1": "old value"}

# Changing an existing element
my_dict["key1"] = "new value"
print(my_dict["key1"]) # Output: new value

# Adding a new element
my_dict["key3"] = "value3"
print(my_dict)  # Output: {'key1': 'new value', 'key3': 'value3'}

To combine dictionaries, you can use the .update() method:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2) # Key 'b' will be overwritten, 'c' will be added
print(dict1) # Output: {'a': 1, 'b':3, 'c':4}

Deleting elements

There are several ways to delete items in dictionaries.:

  • Using the del operator Deletes a key pair. Causes a KeyError error if the key is not found.
    del my_dict["key1"]
    
  • Using the .pop() method Deletes an element by key and returns its value. This is useful if you need to use a deleted value. If the key is not found, it will cause a KeyError, but you can pass the default value.
    my_dict = {'key2': 'value2', 'key3': 'value3'}
    value = my_dict.pop("key2")
    print(value) # Output: value2
    print(my_dict)  # Output: {'key3': 'value3'}
    
  • Deleting all elements The .clear() method clears the dictionary, making it empty.
    my_dict.clear()
    print(my_dict)  # Output: {}
    

Iterating through dictionary elements

1. Key iteration This is the default behavior when iterating through the dictionary.

for key in my_dict:
    print(key)

2. Iterating through values Use the .values() method if you only need values.

for value in my_dict.values():
    print(value)

3. Iterating through key-value pairs This is the most efficient and readable way if you need both keys and values at the same time. Use the .items() method.

for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
main.py
测试 1
测试 2
测试 3
测试 4
测试 5
测试 6
测试 7
测试 8
测试 9
测试 10
开发者解答

🎉 恭喜! 🎉

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

AD

广告

red-snake blue-snake green-snake

正在运行代码...

AI助手

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