.count (' a ')) #统计aPrint (L2.index (' A ')) # Find the index of aL2.insert (2, ' Insert ') # InsertL2.remove (' a ') #删除L2.sort () # Sort, mainly alphabeticallyL2.clear () # Empty AllFor i in L2: # Loop Traversal, note to add : Print (i)2, Dictionary# Dictionary similar to the MAP in Java has key and valuedic={' s1 ': ' Dong Jintao ',' s2 ': ' Male ',' S3 ': ' A ',}dic[' S4 ']= ' Han ' # adddic[' S3 '
','Egon','Zhangquan Egg','li Tie Egg','Oldboy'}stus_python={'li er ya','wxx','Liudehua','Alex','Egon'enroll both Linux and Python students: intersectionPrint(Stus_linux Stus_python)Print(Stus_linux.intersection (Stus_python)) All students: the collectionPrint(Stus_linux |Stus_python)Print(Stus_linux.union (Stus_python)) only registered Linux, not registered python: Difference setPrint(Stus_linux-Stus_python
This article focuses on the use of the clear () method of manipulating dictionaries in Python, which is the basics of getting started with python, and needs friends to refer to the
The clear () method deletes all items in the dictionary (empty the dictionary)
Grammar
The
Functions and descriptions
Example
1
Len (dict)Calculates the number of dictionary elements, that is, the total number of keys.
>>>={' Name ':' Runoob ',' age ':7,' Class ':' First '}>>> len(dict)3
2
STR (DICT)The output dictionary, expressed as a printable string.
>>>={' Name ':' Runoob ',' age ':7,' Class ':' First '}>>> str(dict)"{' Name ': '
The dictionary is the only built-in mapping type in Python.Create dictionary phonebook = {' Alice ': ' 2341 ', ' Beth ': ' 9102 '}You can use Dict to build a dictionary from a sequence of other mappings or key-value pairs. Key value parameter to create a dictionary.The number of items in Len (d) d. D[K] Returns the value associated to the key, d[k] = v assigns th
Custom Create ordered dictionary classesDict's __getitem__ method is somewhat different and wants to use a custom __getitem__ method to display the subscript of the query key;#/usr/bin/env python3#-*-coding:utf-8-*-# author:zshaoxclass mydict (dict): li = [] #定义列表用于有序的排列key值 def __setitem__ (self, Key, value): #自定义__setitem__方法, extending the parent class method Self.li.append (key) #将对象的key added to the list super (mydict, SE
in a dictionaryThe Dict () constructor can create a dictionary directly from the key-value pairDict ([' Tim ', 123), (' Tiny ', 234)]) >>>{' Tiny ': 234, ' Tim ': 123}Derivation creates a dictionary:{d2:d2+ ' @main. com ' for D2 in List (D.keys ()}}>>>{' Jack ': ' [email protected] ', ' Tom ': ' [email protected] '}Exercise: A key-value pair in a circular output dictionary:For Name,email in D.items ():Prin
First, define a dictionaryCreated with {}, each key value in the dictionary is key=>value with a colon : split, separated by commas , between each key-value pair shenyang={' name ': ' Shenyang ', ' age ': ' Sex ': ' Male ', ' addr ': ' Tian Tong Yuan ', ' qq ': ' 19322 ', ' email ': ' [email protected] 'Second, the judgmentNon-NULL is true, not 0 is trueFor example: (if the contents of the E variable have the data true, the empty print is false)E= "If
pairDict ([' Tim ', 123), (' Tiny ', 234)]) >>>{' Tiny ': 234, ' Tim ': 123}Derivation creates a dictionary:{d2:d2+ ' @main. com ' for D2 in List (D.keys ()}}>>>{' Jack ': ' [email protected] ', ' Tom ': ' [email protected] '}Exercise: A key-value pair in a circular output dictionary:For Name,email in D.items ():Print (Name,email)4. CollectionEmpty collection: A = set () ※ to create an empty collection, you must use Set ()Demonstrate:Basket = {' Appl
Dictionaries
The dictionary can be understood as an upgraded version of the listList
list={"Dandan", "Zhangsan", "Wangwu"}
Dictionary
dic={' name ': ' Faint ', ' sex ': ' Man ', ' professional ': ' Computer Science and Technology '}
If you need to modify the "Zhangsan", you need to find its subscript, and the dictionary
a list of keys (key) or values (value) of the dictionary (dict)1. Sort by the key of the dictionary (dict) [1]Copy the Code code as follows:
def sorteddictvalues (Adict,reverse=false):
Keys = Adict.keys ()
Keys.sort (Reverse=reverse)
return [Adict[key] for key in keys]
If you need to return both the key and the value, replace the last return statement with the following:
Copy CodeThe code is as follows:
Tuple definitionA tuple is another data type, similar to a list.The tuple is identified with a "()". The inner elements are separated by commas. However, an element cannot be assigned two times, which is equivalent to a read-only list.Example:tuple = (' ABCD ', 786, 2.23, ' John ', 70.2)list = [' ABCD ', 786, 2.23, ' John ', 70.2]Tuple[2] = 1000 # tuples are illegal to applyList[2] = 1000 # is a legitimate application in the listPrint tuple * 2 # output tuple two timesDictionary definitionsThe
This article mainly introduces the basic knowledge of the dictionary in Python. It is the basic knowledge in the Python getting started. If you need it, you can refer to the dictionary as variable, you can also store any number of Python objects, including other container ty
Common dictionary constants and actions
Operation
Explain
D = {}
Empty dictionary
D = {' spam ': 2, ' Egg ': 3}
Two-item dictionaries
D = {' food ': {' Ham ': 1, ' Egg ': 2}}
Nesting
D = Dict.fromkeys ([' A ', ' B '])
Other construction techniques
D = dict
': $, ' str ': ' Test '}#删除字典元素和字典del dict3[' str '] #删除键位 ' str ' dataPrint dict3 #{' age ': 22}Del Dict2 #删除整个字典#print dict2 #NameError: Name ' Dict2 ' is not definedDict3.clear () #清除dict3字典所有数据Print Dict3 #{}print '--------------------------------------'#遍历字典元素-In the loop, the value of each key of the dict1 is extracted and given to the key variable. For key in Dict1:Print Dict1[key]#字典常用的内置函数Print CMP (DICT1,DICT3) #大于返回1, equal to return 0, less than return-1, key-by-button comparisonPri
element according to key value, if not present, return none2 Print(person1['name'])3 Print(Person1.get ('name'))4 Print(Person1.get ('name1','haha'))#If it does not exist, you can also set a default value5 6 7 dictionary operations: adding, modifying8 (if key does not exist, a new key-value pair will be added, and if present, the values of the key corresponding will be modified)9D = {'name':'Tom',' Age': 22}TenC |'Sex']='Mans' One Print(d)##输出结果: {'
Java and Python use Youdao dictionaries to make search word scripts
Two pictures first, look at the effect.In Java:Python's:
Today's whim, want to do a check word of things, hurriedly go Youdao dictionary website looked, the original we want to query the word is embedded in the Web address to the Youdao dictionary, an
inside the newline character, are changed to \nb# binary # three mode. Read () #读取文件的所有内容, return a string. ReadLines () # Reads all the contents of the file, returns a list, and the contents of each row is an element of the list. ReadLine () #读一行for i in F:print (i). Write () #写一个list. Seek ( ) #移动文件的指针到xx位置. Tell () #查看文件当前的指针在哪里. Truncate () #清空文件. Close () #关闭文件. Flush () #立即把内存里面的数据写到文件里面with open (' xx ') as FW:FW. () If you want to modify the original file, you must create a new file, th
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.