dictionary practice questions

dic = { ' k1 ' : ' v1 ' , ' k2 ' : ' v2 ' , ' k3 ' : ' v3 ' }

# 1. Convenience all keys 
for i in dic:
     print (i)

# 2. Facilitate all the values

for i in dic:
    print (dic[i])

# 3. Convenience all keys and values 
​​for i in dic:
     print (i,dic[i])

# 4. Add key-value pair, 'k4': 'v4', output the added dictionary 

dic[ ' k4 ' ]= ' v4 '

print (Dec)

# 5. Delete the k1 key-value pair 

dic.pop( ' k1 ' )
 print (dic)

# 6. Delete k5, if it does not exist, no error will be reported, and return none 

dic.pop( ' k5 ' ,None)
 print (dic)


# 7. Get the value corresponding to k2

print(dic['k2'])

# 8. Get the value of k6, if it does not exist, no error is reported, and return none 
print (dic.get( ' k6 ' ))

# 9. Existing dic2 = {'k1':'v111','a':'b'}, through one line operation, dic2 ={'k1': 'v1', 'a': 'b', 'k2 ': 'v2', 'k3': 'v3'} 

dic = { ' k1 ' : ' v1 ' , ' k2 ' : ' v2 ' , ' k3 ' : ' v3 ' }
dic2 = {'k1':'v111','a':'b'}
dic2.update(dic)
print(dic2)

# 10. Completion requirements 
lis =[[ ' k ' ,[ ' qwe ' ,20,{ ' k1 ' :[ ' tt ' ,3, ' 1 ' ]},89], ' ab ' ]]

# 1. Change 'tt' in lis to uppercase 
print (lis[0][1][2][ ' k1 ' ][0].swapcase())
 print (lis[0][1][2] [ ' k1 ' ][0].upper())
 # 2. The number 3 in the list becomes the string '100' 
lis[0][1][2][ ' k1 ' ][1] = ' 100 '

print (lis)

# 3. The string 1 in the list becomes the number 101 
lis[0][1][2][ ' k1 ' ][2] = 101
 print (lis)

# 11. Implementation function: if 
# 1 in the dictionary dic , there is no k1, create k1, and add the corresponding element whose index bit in Li is an odd number to the empty list corresponding to k1 
# 2. If there is k1, and the corresponding value of k1 is a list, add the element whose corresponding index bit in Li is odd to the corresponding value of k1 
li = [1,2,3, ' a ' , ' b ' ,4, ' c ' ]
l = []
dic = {'k1':123}
for j in range(0,len(li)):
    if j % 2 != 0:
        l.append(li[j])
print (l)


if dic.get('k1') == None:
    dic['k1'] = l
else:
    if type(dic['k1']) == list:
        dic['k1'] = l

print (Dec)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325316827&siteId=291194637