We have learned about the container data types in Python: lists (list) and tuples (tuple).
1. Definition of Dictionary
A dictionary is a collection of elements consisting of multiple key-value pairs, enclosed in curly braces { }. Keys and values are connected by a colon : , and elements are separated by commas, .Elements in a dictionary exist in the form of key-value pairs, where each element consists of two values separated by a colon, with the key before the colon and the value after it.
dic1 = {"草果":8,"梨":6,"香蕉":5}
【Note】Each key-value pair is an element. Dictionaries do not have indices.
2. Operations on Dictionaries
1. To retrieve values from a dictionary, since dictionaries do not have indices, use the key to parse the corresponding value. This means using the key to replace the indices used in lists and tuples.
dic1 = {"草果":8,"梨":6,"香蕉":5}print(dic1["梨"]) # Retrieve / View the value corresponding to the key 梨
The result is: 62. Modifying values: The method to modify values in existing key-value pairs is similar to that in lists.
dic1 = {"草果":8,"梨":6,"香蕉":5}print(dic1["梨"])dic1["梨"] =10 # Modify the value corresponding to the key 梨print(dic1["梨"])
The result is:
610
3. Adding new elements (key-value pairs):
dic1 = {"草果":8,"梨":6,"香蕉":5}print(dic1["梨"])dic1["梨"] =10print(dic1["梨"])dic1["大米"] = 3.5 # Add new elementprint(dic1)
The result:
610{'草果': 8, '梨': 10, '香蕉': 5, '大米': 3.5}
4. Deleting elements (key-value pairs): Use pop( ) or del function
dictionary_name.pop("existing_key")del dictionary_name["existing_key"]
【Note】In both methods, the position of the dictionary name is different; one uses parentheses for pop, while del uses square brackets.Example:
dic1 = {"草果":8,"梨":6,"香蕉":5}print(dic1["梨"])dic1["梨"] =10print(dic1["梨"])dic1["大米"] = 3.5print(dic1)dic1.pop("梨") # Delete the element with key 梨# del dic1["梨"] # Same effect as the previous lineprint(dic1)
The result:
610{'草果': 8, '梨': 10, '香蕉': 5, '大米': 3.5}{'草果': 8, '香蕉': 5, '大米': 3.5}
Summary: CRUD operations on dictionariesCreate: dictionary_name[“new_key”] = new_valueDelete: ① dictionary_name.pop(“existing_key”) ② del dictionary_name[“existing_key”]Update:dictionary_name[“existing_key”] = new_valueRetrieve:dictionary_name[“existing_key”] Test:
dic2 = {"name":"Anne","age":11,"性别":"女"}print(dic2["name"],dic2["age"])
3. Methods of Dictionaries
1. dictionary_name.values() : Returns all values in the dictionary as a list
2. dictionary_name.keys(): Returns all keys in the dictionary as a list
3. dictionary_name.items(): Returns a traversable array of (key, value) tuples as a list
4. len(dictionary_name): Counts the number of elements in the dictionary, i.e., the total number of keys
5. del dictionary_name: Deletes the entire dictionary, making it non-existent
6. dictionary_name.clear(): Clears all elements in the dictionary, making it an empty dictionary
7. dictionary_name.update(dictionary_name2): Updates (copies) elements from dictionary2 into the dictionary
8. dictionary_name.get(“existing_key”): Returns the value corresponding to the key
dic3 ={"酸辣土豆丝":18,"清蒸鲈鱼":58,"黄豆焖凤爪":38,"羊汤烩面":16}print(dic3.get("清蒸鲈鱼"))print(dic3.values())print(dic3.keys())print(dic3.items())print(len(dic3))dic2={"羊汤烩面":16}dic3.clear()dic3.update(dic2)print(dic3)del dic3
The result:
58dict_values([18, 58, 38, 16])dict_keys(['酸辣土豆丝', '清蒸鲈鱼', '黄豆焖凤爪', '羊汤烩面'])dict_items([('酸辣土豆丝', 18), ('清蒸鲈鱼', 58), ('黄豆焖凤爪', 38), ('羊汤烩面', 16)])4{'羊汤烩面': 16}
【Note】Unlike index operations, the get method does not raise an exception (i.e., does not throw an error) when the specified key does not exist in the dictionary; instead, it returns None or a specified default value.4. Practical Exercises
Example 1: Input a sentence and count the occurrences of each English letter, outputting them in descending order of frequency.
sentence = input('Please enter a sentence: ')counter = {}for ch in sentence: if 'A' <= ch <= 'Z' or 'a' <= ch <= 'z': counter[ch] = counter.get(ch, 0) + 1sorted_keys = sorted(counter, key=counter.get, reverse=True)for key in sorted_keys: print(f'{key} appeared {counter[key]} times.')
The result:
Please enter a sentence: I'm a big big girl, in a big big world.i appeared 6 times.g appeared 5 times.b appeared 4 times.a appeared 2 times.r appeared 2 times.l appeared 2 times.I appeared 1 times.m appeared 1 times.n appeared 1 times.w appeared 1 times.o appeared 1 times.d appeared 1 times.
Example 2: If you are a librarian and need to input information for multiple books, how would you handle it?
Tip:① Define a variable to input all book names, separated by spaces; ② Use the modification method to store it in the value corresponding to the key book in the dictionary; ③ Output the contents of the dictionary.
Code example:
# Prepare variable data, can also store fixed informationinfo = {"room_number":"TSG002"}bookid = input("Please enter book IDs:").split()book = input("Please enter book names:").split()info["bookid"] = bookidinfo["book"] = book# View dictionary contentprint(info)
【Note】① split( ) without a separator defaults to separating by spaces, outputting a list. ② The values of a dictionary can be lists and can be modified, but keys cannot (cannot be lists and cannot be modified).The result:
Please enter book IDs: 1 2 3 4Please enter book names: A B C D{'房间号': 'TSG002', 'bookid': ['1', '2', '3', '4'], 'book': ['A', 'B', 'C', 'D']}
Example 3: Save stock codes and prices in a dictionary, find stocks with prices greater than 100 yuan and create a new dictionary.
Tip: You can use dictionary comprehension syntax to create this new dictionary
stocks1 = { 'AAPL': 191.88, 'GOOG': 1186.96, 'IBM': 149.24, 'ORCL': 48.44, 'ACN': 166.89, 'FB': 208.09, 'SYMC': 21.29}stocks2 = {key: value for key, value in stocks1.items() if value > 100}print(stocks2)
The result:
{'AAPL': 191.88, 'GOOG': 1186.96, 'IBM': 149.24, 'ACN': 166.89, 'FB': 208.09}