Home > front end >  How to retrieve specific parts of dictionary in python
How to retrieve specific parts of dictionary in python

Time:01-21

I want to only retrieve 'left_eye' and 'right_eye' from this dictionary and use them in a different python file.

'keypoints': {
        'left_eye': (int(keypoints[0]), int(keypoints[5])),
        'right_eye': (int(keypoints[1]), int(keypoints[6])),
        'nose': (int(keypoints[2]), int(keypoints[7])),
        'mouth_left': (int(keypoints[3]), int(keypoints[8])),
        'mouth_right': (int(keypoints[4]), int(keypoints[9])),
}

In my other python file I am able to retrieve all of them by using .items()

def face_points():

    add = find_axis().add_patch
    
    for value, number in i ['keypoints'].items():

        add(shape.Circle(
        number, 
        color='white', 
        radius=1, 
        fill=True))

face_points()

Is there a way I can only use 'left_eye' and 'right_eye' without having to edit the dictionary?

CodePudding user response:

operator.itemgetter returns a callable that will get only the items you specify.

Assuming i is a mapping that contains keypoints

import operator

what_i_want = operator.itemgetter('left_eye','right_eye')
left,right = what_i_want(i['keypoints'])

CodePudding user response:

It's as simple as: i['keypoints']['left_eye']. Just don't use it inside that for loop.

  •  Tags:  
  • Related