example:In [176]: Dict = {' name ': ' Zara ', ' age ': 7, ' name ': ' Manni '};in [177]: Print dict[' name ']manni2) The key must be immutable, so it can be used as a number, a string, or a tuple, so you can't use a list.Dictionary built-in functions methodsThe Python dictionary contains the following built-in functions:
Serial Number
Funct
This article mainly introduces the basics of python, including file input and output, built-in types, dictionary operations, and other usage methods.
I. variables and expressions
The code is as follows:
>>> 1 + 12>>> Print 'Hello world'Hello world>>> X = 1>>> Y = 2>>> X + y3
Python is a strongly typed language and
, return noneIf the dictionary is empty and the function is used, the dictionary is empty times wrong(2) The second type: Dic.popitem () The function does not have to fill in the parameters, it randomly deletes a key-value pair. If the dictionary is empty, use this function to error(3) The third type: Dic.clear (), the function does not have to fill in the parame
Adding and traversing Python dictionary key-value pairsTo add a key-value pairFirst define an empty dictionarydic={}1Assign a value directly to a key that does not exist in the dictionary to adddic[' name ']= ' Zhangsan 'Dic{' name ': ' Zhangsan '}123If key or value are variables, you can also use this methodKey= ' age 'Value=30Dic[key]=valueDic{' Age ': +, ' nam
1. A simple dictionaryAlien_0 = {' Color ': ' green ', ' Points ': 5}Print (alien_0[' color ')Print (alien_0[' points ')The dictionary alien_0 stores the aliens ' colors and points. Use two print statements to access and print this information, such asis shown below:Green52.
;>> x=1
>>> y= (x=x+1)
Syntaxerror:invalid syntaxWith #! The beginning is called the organization Line, which tells your Linux/unix system which interpreter to run when you execute your program. Example: #!/usr/bin/python
The line that begins with # is called a comment.
Second, conditional statements
Control flow statements: Arbitrary conditional expressions can be established by using the Or,and,not keyword
If-elif-else: (
can be constructed as shown in the following figure:
Let's analyze the picture above. In addition to the root node, each child node stores only one character. Go and Golang share the go prefix, PHP, Perl, and Python only share the P prefix. To implement dictionary sorting, the characters stored on each layer are stored in a dictionary-sorted manner (this is r
Http://btmiller.com/2015/04/13/get-list-of-keys-from-dictionary-in-python-2-and-3.htmlGet a List of Keys from a Dictionary in Both Python 2 and Python 3It was mentioned in an earlier post this there is a difference on how the keys() operation behaves between
(): if value == value_to_get: print key
Result: 83682
That is, the abcdef encoding in the dictionary.
I hope this article will help you with Python programming.
How to sort Python dictionaries, for example
In Python2.7.x, OrderedDict is added to the collections class. The usage is as follows: In Python2.7.x, Ordere
In-depth Python (1): dictionary sorting about sort (), reversed (), sorted (), reversedsorted
Http://www.cnblogs.com/BeginMan/p/3193081.html
I. Sorting of Python
1. reversed ()
This is easy to understand. The reversed clause is reverse.
print list(reversed(['dream','a','have','I']))#['I', 'have', 'a', 'dream']
2. Conf
() deletes the dictionary, without it in memory, not for "null".Example 6:>> y{' lang ': [], ' name ': ' WTF '}>> del (y)>> yTraceback (most recent):File "Nameerror:name ' y ' is not defined
Get,setdefaultThe meaning of Get is:Help (Dict.get)Get (...)D.get (K[,d]), D[k] if k in D, else D. D defaults to None.Description: "If k in D" returns its valueExample 7:
>> D{' lang ': ' Python '}>> d.ge
. TuplesLists are similar to tuples, lists are mutable, tuples are immutable# # String Conversion Narimoto Group:str1 = ' ABCDEFGHIGKLMN 'Print (tuple (STR1))(' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' g ', ' k ', ' l ', ' m ', ' n ')# # Tuple AA = (' A ', ' B ', ' C ', ' abc ', ' Hello ')When you have a single tuple, be careful to add commas :b = (' mn ',)Print (type (b))Otherwise, th
The dictionary is the only built-in mapping type in Python. The values in the dictionary are not in a particular order, but are stored in a particular key.
A key can be a number, a string, or even a tuple.
1. Creating and Using dictionaries
Dictionaries can be created in the following ways:
Copy Code code as follows:
Phonebook = {' Alice ': ' 2341
contents of the list, enter the B,\N3: Enter the module please input Q,\N4: Return to the upper level Please enter D") if choice.lower () = = "C": Chazh AO = input ("Please enter the name of the list to view") if Chazhao in Diejia:key_case.append (Chazhao) Else:print (" The list name does not exist ") elif choice.lower () = =" B ": Tianjia = input (" Please enter what you want to add to this list ") if Tianjia in Diejia: Print (
First, the dictionaryA dictionary in Python is not a sequence, but rather a mapping; it is stored by key instead of by location. The dictionary is mutable. 1. Dictionary Mapping OperationsUsing the {} definition dictionary to store data in key:value form, key is unique in th
'))#similar to get (), but if the key does not exist in the dictionary, the key is added and the value is set to defaultPrint('Dict1.setdefault (key):', Dict1.setdefault ('Sex', None))Print("dict1.setdefault (' sex '):", Dict1) Dict1={'name':'SJL',' Age': 20,'Address':'Xian'}dict2={'Sex':'Girl'}dict1.update (DICT2)#update the key/value pairs of dictionary dict2 t
relational data.The dictionary is unordered before Python 3.5 contains 3.5, but is ordered after 3.6.2, the dictionary additions and deletions and other operationsThe key is unique when the same key is present in the back of the overlay front. For example:DIC = { ' name ': ' Alex ', ' name ': ' Wusir '}print
to read regular text, modify the list, and then write the file.
['Hello', 'World', 'bye']
Converts a list to a string.
S. split (str, '') # Convert string to list and split with spaces
Storage Dictionary (pickle serialization)
# Import the pickle module import pickle
Store dictionary content into a file
F=file('data.txt ', 'WB') when a new file data.txt, 'WB ', and B is used to open a block file.
Pickle. d
(dict2,10) print (DICT4) #字典 (Dictionary) get () function returns the value of the specified key if the value does not return a default value in the dictionary. dict5={' name ': ' Gyh ', ' Age ':25}print (dict5.get (' name ', ' haha ')) print (Dict5.get (' name ', ' haha '
Dictionary # In Python, the dictionary is a series of key-value pairs. # key-value pairs are separated by:, and key-value pairs are separated
Python learning dictionary of Guibs
# Dictionary # the
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.