简体   繁体   中英

How to get certains keys of a dictionnary and their values with it?

So I have this function that print keys and their values from a dictionnary that contains words in french and their translations in english.

def affiche_dico(dic):
    k_l = list(dic.keys())   #the keys are the french words
    v_l = list(dic.values())   #the values are the translations in english
    i = 0
    for i in range(len(k_l)):
        print(k_l[i], " = ", v_l[i])

My question is, how do I print only keys and their corresponding values just for a certain letter. For example if I want only the words that begins by 'a' how do I do that ?

you can directly iterate over dictionary and no need to store key and value to separate list.

dic = { 'voiture' : 'car' , 'gâteau' : 'cake' , 'voilier' : 'ship'}

for key, value in dic.items():
    if key[0] == 'v' : # comparing v to the first character of key
        print("{} = {}".format(key,value))


voiture = car
voilier = ship

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM