Python data types-tuples, commonly used dictionary operations, python data type dictionary

Source: Internet
Author: User

Python data types-tuples, commonly used dictionary operations, python data type dictionary
Tuples

The Python tuples are similar to the list. The difference is thatThe elements of the tuples cannot be modified..

The tuples use parentheses, And the list uses square brackets.

Creating tuples is simple. You only need to add elements in brackets and separate them with commas.

tp=(1,2,3,'a','b')
A = 'Hello world' # This is defined as str type B = ('Hello World') # If there is only one element when defining tuples, then the type of B is strc = ('Hello world',) print (type (c ))

The tuples only have the count and index methods, as shown below:

Tp = ('2017. 0.0.1 ', '000000',' B ', 'A', '000000', 1, 2, 3, 1, 44) print (tp [0]) # print (tp. count ('200') # query the number of times that an element appears in the tuples print (tp. index ('A') # search for the index location of an element

Forced type conversion of tuples:

Lis = [1, 2, 3, 4, 5, 'B', 'C'] new_lis = tuple (lis) # convert the mandatory list type to tupleprint (type (new_lis ))

Currently, functions that can force type conversion include int (), str (), float (), list (), and tuple ()

Dictionary

The dictionary is another variable container model that can store any type of objects. The data stored in the dictionary is unordered.

Each key-value (key => value) pair of the dictionary uses the colon (:), And each pair is separated by a comma (,The entire dictionary is included in curly brackets ({})The keys in the dictionary cannot be repeatedly defined. The format is as follows:

d = {key1 : value1, key2 : value2 }

The following describes how to obtain dictionary elements:

# Dictionary. The key cannot be repeated during definition. info = {'name': 'xiaoming', 'sex': 'man', 'age': 20, 'id ': 1} # differences between the two value methods: If the Input key does not exist, an error is returned when you use the [] value. If you get the value, Noneprint (info ['name']) is returned. # dictionary value, obtain the corresponding valueprint (info. get ('name') # You can also get it by using the get method, get (key) print (info. get ('addr ', 'beijinging') # If the Input key does not exist, the default value beijing is returned. If the Input key is not written, None is returned.

Add a dictionary element as follows:

# Add the element info ['add'] = 'beijing' # You can use the [key] = value Method to add the element. If the key does not exist, print (info) info is added. setdefault ('phone', '000000') # You can also use the setdefault (key, value) method to add the print (info) element)

Modify the elements in the dictionary as follows:

Info ['id'] = 7 # If the key exists, the value corresponding to the key is modified. If the key does not exist, the print (info) element is added to the method)

Delete the elements in the dictionary as follows:

# Delete del info ['add'] # Delete the element info. pop ('addr ') # The dictionary is unordered. Input The key To be deleted. The pop method returns the valueprint (info) corresponding to the deleted key # info. pop ('kk ') # If the deleted key does not exist, the following error occurs: KeyError: 'kk' info. clear () # clear the dictionary info. popitem () # It is of little use to randomly delete an element.

The following figure shows the elements of the dictionary loop traversal:

Info = {'name': 'xiaoming', 'sex': 'man', 'age': 20, 'id': 1} print (info. keys () # obtain all keys of the dictionary. Execution result: dict_keys (['name', 'age', 'sex', 'id']) print (info. values () # obtain all values of the dictionary. Execution result: dict_values (['xiaoming', 20, 'man', 1]) print (info. items () # print all the keys and values and use them cyclically. Execution result: dict_items ([('name', 'xiaoming'), ('age ', 20), ('sex', 'man'), ('id', 1)]) # dictionary looping for k, v in info. items (): print ('key: % s value: % s' % (k, v) execution result: key: age value: 20key: sex value: mankey: name value: xiaomingkey: id value: 1

Dictionary update usage:

Info = {'A': 'xiaoming', 'sex': 'man', 'age': 20, 'id': 1} info2 = {'A': 1, 'B': 2} info. update (info2) # merge the two dictionaries into one. If there is the same key, update the value. Execution result: {'sex': 'man', 'id ': 1, 'B': 2, 'age': 20, 'A': 1}
Print (info)

Exercise: Define a dictionary, modify the values in the dictionary, and change the yellow color to green, as shown below:

all = {    'car': {        'color': ['red', 'yellow', 'black'],        'money': 1111,        'name': 'beijing'    },    'car1': {        'id': [1, 2, 3],        'money': 222,        'name': 'shanghai'    },    'car2': {        'city': ['beijing', 'shanghai', 'zhengzhou'],        'money': 3333,        'name': 'henan'    }}

The Code is as follows:

Car_value = all. get ('car') # The returned value is a dictionary. The execution result is {'name': 'beijing', 'color': ['red', 'yellow ', 'black'], 'money': 1111} print (car_value) color_list = car_value.get ('color') # The returned result is list. Find the corresponding value based on the key. The execution result is as follows: ['red', 'yellow', 'black'] print (color_list) color_list_value = color_list [1] # list returns the result yellowprint (color_list_value) based on the subscript value) color_list [1] = 'green' # change the value of the list and Change yellow to greenprint (all. get ('car') # execution result: {'money': 1111, 'color': ['red', 'green', 'black'], 'name ': 'beijing '}

 

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.