How to add elements to python dictionary: 1. Add elements through "book_dict["owner"]="tyson"" syntax; 2. Through "book_dict.update({"country": "china"}) " method to add elements; 3. Add elements through the "book_dict.update(temp = "", help = "") " method; 4. Add elements through the update method, and the parameter is the dictionary unpacking method.
The operating environment of this tutorial: Windows 10 system, python3 version, DELL G3 computer
What is the method to add elements to the python dictionary?
Add elements to Python dictionary
This article uses code
book_dict = {"price": 500, "bookName": "Python设计", "weight": "250g"}
The first way: use []
book_dict["owner"] = "tyson"
Description: Square brackets specify the key and assign a value. If the key does not exist, the element is added (if the key already exists, the value corresponding to the key is modified)
Two methods: use the update() method, the parameter is a dictionary object
book_dict.update({"country": "china"})
Description: Use the update() method of dict and pass in a new dict object. If the key does not exist, add it. element! (If the key in this new dict object already exists in the current dictionary object, the value corresponding to the key will be overwritten)
The third way: use the update() method, parameters For keyword parameters
book_dict.update(temp = "无语中", help = "帮助")
Note: The update method of dict is also used, but the keyword parameters are passed in. If the key does not exist, the element is added (if the key exists, the value is modified)
Note: In the keyword parameter form, the key object can only be a string object
The fourth way: use the update() method, the parameter is the dictionary unpacking method
my_temp_dict = {"name": "王员外", "age":18} book_dict.update(**my_temp_dict)
is equivalent to
book_dict.update(name="王员外",age=18)
Note: The dictionary is a completely unordered mapping collection
1. The dictionary is unordered: When you traverse the dictionary elements, the order in which you add the elements, and The order in which you access elements makes no difference! (Note: Starting from the Python 3. This is just a coincidence. For a dictionary that requires ordered elements, please see OrderedDict
Recommended study: "
Python Video TutorialThe above is the detailed content of What is the method to add elements to python dictionary. For more information, please follow other related articles on the PHP Chinese website!