Python tips for processing lists and dictionaries

1. Get the key corresponding to the largest value in the dictionary

key = max(my_dict, key=my_dict.get)

example

Insert picture description here

2. Randomly select an element from a list or dictionary

import random
2.1 Randomly select an element from the list
random_value = random.choice(my_list)

Insert picture description here

2.2 Randomly select the key or value of an element from the dictionary
random_key = random.choice( list( my_dict.keys() ) )
random_value = random.choice( list( my_dict.values() ) )

Insert picture description here

Three, according to the dictionary value to find the corresponding key

key_list = list( filter(lambda key:my_dict[key] == value, my_dict) )

Insert picture description here

Fourth, delete a key-value pair in the dictionary

my_dict = my_dict.pop(key)

Insert picture description here

Continue to accumulate...

Guess you like

Origin blog.csdn.net/SL_World/article/details/108033604