user2355903
user2355903

Reputation: 643

Selecting Key,Value pairs from Key values in another dictionary

I'm trying to select all of the key,values from one dictionary (imgs_dict) that have a key that appears in another dictionary (train_data_labels) and save the result into a third dictionary (training_images). One of the two original dictionaries has keys that are stored as numeric values (train_data_labels) and one is stored as a string (imgs_dict), so I first try to convert the key values of train_data_labels to a string and add leading zeros to match structure of imgs_dict, but this creates a list rather than a dictionary.

# Add leading zeros and convert key values to strings to allow referencing the image dictionary
training_ids=[str(k).zfill(5) for k in train_data_label]

After this I am trying to pull the image ids appearing in training_ids from imgs_dict, this appears to work but creates a list rather than a dictionary.

# Pull the training images from the total image set and save in a training images dictionary
training_images=[imgs_dict[i] for i in training_ids if i in imgs_dict]

It seems like there should be a straight forward way to save a new dictionary with altered keys, then select certain dictionary items that you want from another dictionary based on another list or dictionary but I'm having trouble finding it.

Upvotes: 0

Views: 39

Answers (1)

Robert Kearns
Robert Kearns

Reputation: 1706

You could use a dictionary comprehension instead of the second list comp.

training_images = {key: imgs_dict[key] for key in training_ids if key in imgs_dict}

Upvotes: 0

Related Questions