Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 470
uhuuyouneverknow Avatar asked Jun 08 '17 11:06

uhuuyouneverknow


2 Answers

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.

like image 195
Chris Mueller Avatar answered Nov 19 '22 08:11

Chris Mueller


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).

like image 32
harshil9968 Avatar answered Nov 19 '22 10:11

harshil9968