Python takes out multiple value values corresponding to multiple keys of dict at one time

Python takes out the value corresponding to multiple keys of dict at one time


Mainly because in the coding process, sometimes we need to take out a lot of values ​​corresponding to the keys we need for processing. Need to import the package from operator import itemgetter
the default output is sorted according to the key sequence
following code:

def get_keys_from_dict():
    from operator import itemgetter
    aa = {
    
    1:2,3:4, 5:6}
    print(aa)
    keys = [1,3]
    # need make sure keys in dict_key
    out = itemgetter(*keys)(aa)
    print(out)
    return

if __name__ == '__main__':
    get_keys_from_dict()

The output is as follows:

{1: 2, 3: 4, 5: 6}
(2, 4)
[Finished in 0.9s]

Guess you like

Origin blog.csdn.net/qq_32507417/article/details/107442731