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 :)
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
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With