A dictionary is a data structure of python, such as a set of mappings in mathematics, that can be understood as a list of elements that exist by key and value pairs.
A. Dictionary construction form:
1. Dictionary name = {Key Name 1: value 1, key Name 2: Value 2, key Name 3: Value 3}
For example:D IC = {' op ': 3: (' A ', ' B '), ' Q ': [1.25, ' score ', 5]}
Where keys can only be immutable objects (such as tuples, strings, integers, etc.) and the values may be arbitrary objects
2. You can use Dict () or {} to construct an empty dictionary such as Dic=dict () dic={}
Two. Index of the Dictionary:
1. dictionaries can use the [] operator, but unlike previous list tuples, dictionaries may not use sequential numbers as indexes such as 1,2,-1, etc.
2. the dictionary needs to use the key value as an index, such as 1. In the example, you can use the following index method dic[' op '] dic[3] dic[' Q ']
3. since the value of a dictionary can be any object, it is possible to list, tuple, or even dictionary. Then when the value is the above object, using the dictionary name [key values] method will get a set, so we can use a two-dimensional method to index
Example:
>>> dic={' a ': {' q ': ' Hello ', ' W ': ' How ', ' E ': ' Thanks '}}>>> dic[' a ' [' e '] ' Thanks '
A one-dimensional result is a list, and the two-dimensional [] variable can use the sequential numeric index
And so on, when the value of the two-dimensional key is still a collection of dictionaries, you can continue to use this:
>>> dic={' a ': {' q ': ' Hello ', ' W ': ' How ', ' E ': {' u ': ' Yes '}}}>>> dic[' a ' [' e '] [' u '] ' yes '
4. If the key value entered does not exist at the time of indexing, Python will error
Three. Assignment of dictionaries:
The assignment method is a dictionary name [key Name] = value to form a mapping relationship
When the key name for the assignment does not exist, Python will add the key value pair directly to the dictionary.
Four. Dictionary-related operations:
[]: Use keys in square brackets to index
Len (): The calculated length is the number of key-value pairs in the dictionary
In: Member Test, determines whether the key is in the dictionary
For: Loop to find each key-value pair in the dictionary
Five. Dictionary method:
items (): A list of tuples that generate all key-value pairs
Keys (): Generate a list of all keys
VALUES (): Generate a list of all values
Copy (): A shallow copy of the dictionary (referential relationship)
Six. An example
Take "Gettysburg speech" as an example to analyze, judge the number of words and corresponding frequency, and to sort the display
import stringdef addword (word,wdict): #将word单词加入字典统计, No key-value pairs are added, there is a value of +1 if (word in wdict): wdict[word]+=1 else: wdict[word]= 1def collect (line,wdict): #对line字符串进行分析, and split the valid words into the dictionary line = line.strip () wordline = line.split () for word in wordline: if (word == '---'): continue word = word.strip (string.punctuation) word = word.lower () addword (Word, wdict) def printf (wdict): #对字典内容排序输出函数 resultwords = [[val,key] for Key,val in wdict.items ()] resultwords.sort (reverse=true) print ("%-12s%-10s"% (' word ', ' Count ')) print ('-' *21 ') for count,word in resultwords: if (COUNT>2): print ("%-13s%-3d"% (Word,Count)) Wdict = {} #在这也可以将下面的代码封装到main (), then execute main () to run the program fileodj = Open (' Wordtest.txt ', ' RU ') for line in fileodj: collect (line,wdict) Printf ( WDICT)
Python Learning Diary---Dictionary