I've already introduced python String in data type 、 Tuples and lists , Next, we introduce another data type : Dictionaries .
A dictionary is a kind of disorder (3.6 Order after version ) Object collection for , use {} identification , With key:value In the form of data storage . The elements in the dictionary are through the keys (key) To access , Instead of taking values by index . The elements of the dictionary are key value pairs , key (key) Immutable type must be used , In the same dictionary , key (key) Is the only one. .
Create a dictionary :
a = {} a = {"name":"xiaobo","age":29} b = dict(a) # {"name":"xiaobo","age":29} b = dict([("name","xiaobo"),("age",29)]) # {"name":"xiaobo","age":29}
Dictionary data acquisition :
a = {"name":"xiaobo","age":29} print(a.get('name')) print(a.get('name11')) print(a['name']) print(a['name1'])
Modify dictionary data :
update(): When the data does not exist, create , If it exists, it will be updated
Suppose the dictionary is a = {"name":"xiaobo","age":29}, modify name: a['name']= " Xiaobo " Use update() Function modification : a = {"name":"xiaobo","age":29} row = {"height":173} a.update(row)
Delete the dictionary value :
pop(key) function : According to one key Delete data , return key Corresponding value, When calling a method , Incoming key There must be , Otherwise, an error will be reported :
a = {"name":"xiaobo","age":29} print(a.pop('name')) #xiaobo
popitem() function : Usually delete the last element , Calling this method with an empty dictionary will report an error
a = {"name":"xiaobo","age":29} a.popitem() # remove age data , be left over name a.popitem() # The dictionary becomes empty a.popitem() # Calling this method with an empty dictionary will report an error
clear() function : Empty dictionary .
del Delete some key:
a = {"name":"xiaobo","age":29} del a["name"]
ACCESS Dictionary View :
a = {"name":"xiaobo","age":29} print(a.items()) # dict_items([('name', 'xiaobo'), ('age', 29)]) print(a.keys()) # dict_keys(['name', 'age']) print(a.values()) #dict_values(['xiaobo', 29])
Dictionary summary :
This article is from WeChat official account. - Xiaobo's road to growth (libotest)
The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .
Original publication time : 2021-09-26
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .