Home >Backend Development >Python Tutorial >dictionary in python
Dictionary: an associative array or hash table, an object indexable by keyword.
Purpose of dictionary: Define an object that can contain multiple named fields, and can also be used as a container to quickly find unordered data
Dictionaries are the most complete data type in Python and are most commonly used for storage and processing in programs. Data
How to create:
1, put the value in {} to create an empty dictionary;
2, use the method dict() to create an empty dictionary
data = { "name" : "神行太保戴宗", 'title' :'天速星', 'age' : 45, 'price' : 490 }
To access Dictionary members use the keyword index operator s[name]:
name = data['name']; title = data['title']; age = data['age']; print(name); print(title); print(age);
The output result is:
神行太保戴宗 天速星 45
Methods to insert or modify objects:
data['book'] = '水浒传之梁山108将'; #插入 data['name'] = '插翅虎雷横'; #修改 data['title'] = '天退星';
Output result:
水浒传之梁山108将 插翅虎雷横 天退星
String is a commonly used keyword type
Find unordered data:
prices = { 'apple' :3.4, 'banana' : 4, 'orange' : 2.5, 'lemon' : 3.7, 'pear' : 1.8 }
applePrice = prices['apple'];
Output result:
3.4
How to determine whether an item is a member of the current dictionary:
1, use the in operator to test whether a content item is a member of the dictionary
if "grape" in prices: p = prices['grape']; else: p= 0; print(p);
Output result:
0
2, use the system method get to determine whether it is a dictionary member
p = prices.get('grape',0); print(p);
Output result:
0
Get the dictionary key The list of words only needs to convert the dictionary into a list:
pricelist = list(prices);
Output result:
['orange', 'lemon', 'pear', 'banana', 'apple']
Method to delete dictionary elements del:
del prices['pear'];
Output result:
{'apple': 3.4, 'banana': 4, 'lemon': 3.7, 'orange': 2.5}
Summary:
1. What is the dict dictionary? : is an associative array or hash table
2, create dictionary: 1, {} 2, dict()
2, purpose of dictionary: used to quickly find unordered data and often used to store and process data
3, use dictionary keyword index to obtain data
4, dictionary insertion and modification: use keyword index to add or modify the format s[name] = 'data';
5, determine whether the element exists in the dictionary : 1, in 2, get
6, method to get dictionary keywords: list is declared as list
6, deletes elements in the dictionary: del method
The above is in python Dictionary content, please pay attention to the PHP Chinese website (www.php.cn) for more related content!