uhuuyouneverknow
uhuuyouneverknow

Reputation: 433

Select the key:value pairs from a dictionary in Python

I have a Python Dict like as follows:

a = {"a":1,"b":2,"c":3,"f":4,"d":5}

and I have a list like as follows:

b= ["b","c"]

What I want to do is selecting the key:value pairs from the dict a with keys in b. So the output should be a dictionary like:

out = {"b":2,"c":3}

I could simply create another dictionary and update it using the key:value pair with iteration but I have RAM problems and the dictionary a is very large. b includes a few points so I thought popping from a does not work. What can I do to solve this issue?

Edit: Out is actually an update on a. So I will update the a as out.

Thanks :)

Upvotes: 12

Views: 41267

Answers (4)

aman kumar
aman kumar

Reputation: 1

a = {"a":1,"b":2,"c":3,"f":4,"d":5} b= ["b","c"]

dict1 = {} for key,value in a.items(): for i in b: if i == key: dict1[i] = value dict1

Upvotes: -1

zaidfazil
zaidfazil

Reputation: 9235

You could do this,

a = {"a":1,"b":2,"c":3,"f":4,"d":5}
b= ["b","c"]

out = {item:a.get(item)for item in b}

This won't raise any error, but adds '' if the item is not in a.

Upvotes: 3

harshil9968
harshil9968

Reputation: 3244

If you don't have any problem with modifing the exsisting dict then try this :

out = {}
for key in b:
        out[key] = a.pop(key)

This wouldn't take any extra space, as we're transferring the values required from old to new dict, and would solve the problem of slow selective popping as well(as we're not traversing through all but only the selective one's which are required).

Upvotes: 4

Chris Mueller
Chris Mueller

Reputation: 6680

If you truly want to create a new dictionary with the keys in your list, then you can use a dict comprehension.

a = {"a":1,"b":2,"c":3,"f":4,"d":5}
b = ["b", "c"]

out = {x: a[x] for x in b}

This will fail by raising a KeyError if any of the elements of b are not actually keys in a.

Upvotes: 14

Related Questions