Python Dictionary-related operations

Source: Internet
Author: User

Search and delete of dictionary dictionary

How dictionaries are created:

# Create Dictionary Type info = {    ' name ': ' Li Bai ', ' age ': ' + '    ,    ' sex ': ' male '}msg = {    ' User01 ': ' Longzeluola ',    ' user02 ': ' Xiaozemaliya ',    ' user03 ': ' Cangjingkong '}

When a dictionary stores data, it takes the form of Key:value, which is a set of unordered storage. You can quickly get value by key when you need it.

msg = {    ' User01 ': ' Longzeluola ',    ' user02 ': ' Xiaozemaliya ',    ' user03 ': ' Cangjingkong '}print (msg[' User01 ') )  # Longzeluola

The value of the dictionary can be obtained and changed according to the key value.

msg = {    ' User01 ': ' Longzeluola ',    ' user02 ': ' Xiaozemaliya ',    ' user03 ': ' Cangjingkong '}msg[' user03 '] = ' Laura

Results:

{‘user01‘: ‘Longzeluola‘, ‘user02‘: ‘xiaozemaliya‘, ‘user03‘: ‘泷泽萝拉‘}

If you need to add new data in the dictionary, you can also add it by setting the Key-value form.

msg = {    ' User01 ': ' Longzeluola ',    ' user02 ': ' Xiaozemaliya ',    ' user03 ': ' Cangjingkong '}msg[' user04 '] = ' Malicang ' Print (msg)

Results:

{‘user01‘: ‘Longzeluola‘, ‘user02‘: ‘xiaozemaliya‘, ‘user03‘: ‘cangjingkong‘, ‘user04‘: ‘MaLiCang‘}

If you need to delete data from Python, you can use the following three methods:

msg = {    ' User01 ': ' Longzeluola ',    ' user02 ': ' Xiaozemaliya ', '    user03 ': ' cangjingkong '}# Delete dictionary method one #del msg[' User01 ']  # {' User02 ': ' Xiaozemaliya ', ' user03 ': ' cangjingkong '}# Delete dictionary method two #msg.pop (' User01 ')  # # {' User02 ': ' Xiaozemaliya ', ' user03 ': ' cangjingkong '}# Delete dictionary method three Msg.popitem () # {' User01 ': ' Longzeluola ', ' user02 ': ' Xiaozemaliya '}

Add

In some of the above operations, we basically realize the dictionary additions and deletions, but in the process of checking, there is a point to note, such as the above Query method Dir[key] This, if the key value does not exist in the dictionary, there will be a keyerror error, so in order to avoid errors, In general, we do not use this method to look up the key value of a dictionary, but rather by the following method.

# Create a dictionary msg = {    ' user1101 ': ' Xiaozemaliya ',    ' user1102 ': ' Wutentlan ',    

To determine whether a key exists in a dictionary, you can use the in operator.

# Create a dictionary msg = {    ' user1101 ': ' Xiaozemaliya ',    ' user1102 ': ' Wutentlan ',    ' user1103 ': ' Cangjingkong '}# Use in to detect if the specified Keyprint (' user1101 ' in msg) # Trueprint (' user1109 ' in msg) is present in the dictionary # False

Above is the use of the in operator to determine whether a key exists, it should be noted that in the python2.x version, determine whether a key exists in the dictionary, you can use the Msg.has_key () way to judge.

Multi-level dictionary nesting and manipulation

In the dictionary, the data is stored in the form of key-value, but the value, in addition to the string, can be a value of other types. Also, in a dictionary, you can continue to nest data such as dictionaries. Here's how:

# Create a multi-level dictionary Av_catalog = {"    Europe and America": {        "www.youporn.com": ["many free, world largest", "Quality General"],        "www.pornhub.com": ["a lot of free, Also very big "," the quality is higher than Yourporn High "],        " letmedothistoyou.com ": [" Many is selfies, the quality picture is many "," the resources are not many, the update is slow "],        " x-art.com ": [" The quality is very high, really high "," All charges, Dick than please bypass "]    },    " Japan and Korea ": {"        tokyo-hot ": [" quality is not clear, the individual has not liked the Japanese and Korean fan "," heard is the charge of "]    },    " mainland ": {        " 1024 ": ["All free, really nice, good people all life safe", "server in Foreign, slow"]    }} # change key value av_catalog[' Continental ' [' 1024 '][1] = ' can make a mirror ' print (Av_catalog) in the country

A supplementary explanation of the dictionary

Values print all of the value in the dictionary

msg = {    ' stu1101 ': ' xiaomingstudent ',    ' stu1102 ': ' xiaohongstudent ',    ' stu2201 ': ' Xiaolvstudent ',    ' stu3101 ': ' Xiaozhangstudent '}# values () method output in dictionary all value print (Msg.values ())

The result is:

dict_values([‘XiaomingStudent‘, ‘XiaohongStudent‘, ‘XiaolvStudent‘, ‘XiaoZhangStudent‘])

Keys to print all keys

msg = {    ' stu1101 ': ' xiaomingstudent ',    ' stu1102 ': ' xiaohongstudent ',    ' stu2201 ': ' xiaolvstudent ',    ' Stu3101 ': ' xiaozhangstudent '}# keys print all Keyprint (Msg.keys ())

The result is:

dict_keys([‘stu1101‘, ‘stu1102‘, ‘stu2201‘, ‘stu3101‘])

SetDefault

Set the new Key:value, if the set key exists in the dictionary, then the previous key and value will be returned, the new settings will be invalidated, if not the set of Key:value added to the dictionary.

msg = {    ' stu1101 ': ' xiaomingstudent ',    ' stu1102 ': ' xiaohongstudent ',    ' stu2201 ': ' xiaolvstudent ',    ' Stu3101 ': ' xiaozhangstudent '}# use SetDefault method to set Key:valuemsg.setdefault (' stu3101 ', ' yanyanstudent ') # at this time 3101key already exists, Does not add content to the affected print (msg) msg.setdefault (' stu3102 ', ' lulustudent ') # at this time the newly added key 3102 adds success print (MSG)

Update merge

Using the Update method, you can merge two dictionaries, and if duplicate content exists in the dictionary, an overlay is generated, and if the content is not duplicated, it is merged into a dictionary.

msg = {    ' stu1101 ': ' xiaomingstudent ',    ' stu1102 ': ' xiaohongstudent ',    ' stu2201 ': ' xiaolvstudent ',    ' Stu3101 ': ' xiaozhangstudent '}test_info = {    ' T1101 ': ' Yanyanteacher ',    ' T1102 ': ' Libai ',    ' stu2201 ': ' Jingjingstudent '}msg.update (test_info) print (msg)

The output is:

{‘stu1101‘: ‘XiaomingStudent‘, ‘stu1102‘: ‘XiaohongStudent‘, ‘stu2201‘: ‘JingjingStudent‘, ‘stu3101‘: ‘XiaoZhangStudent‘, ‘T1101‘: ‘YanYanTeacher‘, ‘T1102‘: ‘LiBai‘}

Items convert a list to a tuple

msg = {    ' stu1101 ': ' xiaomingstudent ',    ' stu1102 ': ' xiaohongstudent ',    ' stu2201 ': ' Xiaolvstudent ',    ' stu3101 ': ' Xiaozhangstudent '}print (Msg.items ())

The output is:

dict_items([(‘stu1101‘, ‘XiaomingStudent‘), (‘stu1102‘, ‘XiaohongStudent‘), (‘stu2201‘, ‘XiaolvStudent‘), (‘stu3101‘, ‘XiaoZhangStudent‘)])

Fromkeys creating a list of initialization

The result of the output is:

{‘stu01‘: [1, {‘name‘: ‘YanYanStudent‘}], ‘stu02‘: [1, {‘name‘: ‘YanYanStudent‘}], ‘stu03‘: [1, {‘name‘: ‘YanYanStudent‘}]}

At this point, a new dictionary is created with the Dict.fromkeys method, but there is an error-prone place in the dictionary, as follows:

Test_dir = Dict.fromkeys ([' stu01 ', ' stu02 ', ' stu03 '],[1,{' name ': ' Yanyanstudent '}]) # Try to change the contents of this dictionary by the key value test_dir[' Stu01 '][1][' name '] = ' yanyanteacher ' Print (Test_dir)

We changed the value of one of the keys in the code, and the result output was:

{‘stu01‘: [1, {‘name‘: ‘YanYanTeacher‘}], ‘stu02‘: [1, {‘name‘: ‘YanYanTeacher‘}], ‘stu03‘: [1, {‘name‘: ‘YanYanTeacher‘}]}

At this point we find that all the key corresponding value has been changed. And this is the point we need to be aware of when using this Fromkeys method.

The loop output of the dictionary

The key and value in the dictionary are looped out in the following two ways:

# Create a dictionary msg = {    ' T1101 ': ' Yanyanteacher ',    ' T1201 ': ' Luluteacher ', '    T1301 ': ' jingjingteacher '}# loop output dictionary-- First method for I in msg:    print (i,msg[i]) # Loop Output Dictionary--second method for i,v in Msg.items ():    print (I,V)

The above two output lists are the same as the output, but it is preferable to use the first one, because the first one is more efficient than the second because the first is to take out value directly from the key value, and the second is to step out the dictionary into a list. So the efficiency is comparatively low.

Python Dictionary-related operations

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.