Python3 Exercise 2 list and dictionary exercises

Source: Internet
Author: User

Find the list of values greater than 100, give the dictionary dic's K1 key, less than or equal to 100 of the value, to the dictionary dic K2 key

‘‘‘

Tip: Two ways to create a dictionary

Ex

‘‘‘

V1 = [2,3,4,5== = = {'K1'K2' = Dict (K1 = v1, K2 = v2,) Print (DIC1) Print (DIC2)
List = [2, 5, 9, 20, 27, 80, 100, 110, 127, 158, 166, 198,]dic= {}#define an empty dictionary#method One:L1 = []#define two empty listsL2 = [] forIinchList#loop Find, traverse list element    ifI > 100:#judging when the element value is >100L1.append (i)#adding elements to the list L1    Else: L2.append (i) dic['K1'] = L1#The value of the key K1 of the dictionary dic is L1dic['K2'] = L2#The value of the key K2 of the dictionary dic is L2Print(DIC)#Method Two: forIinchlist:ifI > 100:        if 'K1' inchDic.keys ():#if the key K1 in the key list of the dictionarydic['K1'].append (i)#Append the value of I to the list of values corresponding to the dictionary K1 key        Else: dic['K1'] = [I,]#if the key K1 does not exist, a new K1 key is created, the corresponding value is a list, and the element is the value corresponding to I    Else:        if 'K2' inchDic.keys (): dic['K2'].append (i)Else: dic['K2'] =[I,]Print(DIC)

Python3 Exercise 2 list and dictionary exercises

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.