To find the value with a part of the key in the dictionary, ㅠㅠ

Asked 1 years ago, Updated 1 years ago, 62 views

Like a captured image If the key includes the letter 'third grade', I want to print out the phone numbers of Hong Gil-dong and Hong Gil-soon.What is there to do?! Have a nice day Thank you!

python dictionary keys value

2022-09-22 18:42

2 Answers

Hi, how are you?

dic = {'Hong Gil-dong 3rd grade': '123456', '123456': 'Hong Gil-dong 3rd grade', 'Hong Gil-soon 3rd grade': '456789', '456789': 'Hong Gil-soon'}

find_word = '3rd grade'

For kindic: #k = 'Hong Gil-dong 3rd grade'
    if k.split()[1] == find_word: #k.split() = ["Hong Gil-dong", "third grade"]
        print(dic[k]) #k.split()[1] = '3rd grade'
                                  # dic['3rd grade'] = '123456'

Have a nice day


2022-09-22 18:42

You can use the in operator in the string.

In [1]: dic = { 'Hong Gil-dong 3rd grade': '123456', '123456': 'Hong Gil-dong 3rd grade', 'Hong Gil-soon 3rd grade': '456789', '456789': 'Hong Gil-soon'}

In [2]: for vin (dic.get(key) for key in dic.keys() if 'third grade' in key): # Only the key value of the dictionary contains the third grade.
    ...:     ...:     print(v)

123 456
456 789


2022-09-22 18:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.