sanjayr
sanjayr

Reputation: 1939

Python: select key, values from dictionary corresponding to given list

I have a set dictionary like so:

d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}

Given a list, can I just keep the key, values given?

Input:

l = ['one', 'three']

Output:

new_d = {'cat': 'one', 'fish': 'three'}

Upvotes: 1

Views: 544

Answers (3)

Daniel Dominique
Daniel Dominique

Reputation: 66

The scenario you've described above provides a perfect use case for the IN operator, which tests whether or not a value is a member of a collection, such as a list.

The code below is to demonstrate the concept. For more practical applications, look at dictionary comprehension.

d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
l = ['one', 'three']

d_output = {}

for k,v in d.items():     # Loop through input dictionary
    if v in l:            # Check if the value is included in the given list
        d_output[k] = v   # Assign the key: value to the output dictionary

print(d_output)

Output is:

{'cat': 'one', 'fish': 'three'}

Upvotes: 3

FrancecoMartino
FrancecoMartino

Reputation: 419

You can copy your dictionary and drop unwanted elements:

d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
l = ['one', 'three']
new_d = d.copy()
for element in d:
    if (d[element]) not in l:
        new_d.pop(element)

print(d)
print(new_d)

Output is:

{'cat': 'one', 'dog': 'two', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}

Upvotes: 1

robbo
robbo

Reputation: 545

You can use dictionary comprehension to achieve this easily:

{k: v for k, v in d.items() if v in l}

Upvotes: 8

Related Questions