views:

169

answers:

3

I have a dictionary:

D = { "foo" : "bar", "baz" : "bip" }

and I want to create new dictionary that has a copy of one of it's elements k. So if k = "baz":

R = { "baz" : "bip" }

what I've got now is:

R = { k : D[k] }

But in my case k is a complex expression and I've got a whole stack of these. Caching k in a temporary looks about as ugly as the original option.

What I'm looking for is a better (cleaner) way to do this.

A: 

One way or another, you're going to need a set of items to "slice" out.

S = set(["baz"])

If you had Set S above you could do a dictionary comprehension on D to get R:

R = dict((k,v) for k,v in D.items() if k in S)
EnigmaCurry
If (when) I find I have more than one item that will work but it is overkill in this case.
BCS
+1  A: 
def take(dictionary, key):
    return {key: dictionary[key]}

R = take(D, k)
liori
Does this make it cleaner? It looks to me like you're doing the same thing the OP is (with the same syntax), but moving it somewhere else and adding a function call.
tgray
@tgray: If `k` is a long expression, it does.
liori
+1  A: 

You can't get much "cleaner" than what you have. Assuming your definition of clean is fewer characters.

Adding a function call to do such a simple task seems like it would do more to confuse your code than make it cleaner.

If you definition of clean is more readable, then giving your dictionaries descriptive names (and following PEP-8 in your naming conventions) should do it.

tgray
In this case (the SO question being the case) more descriptive names would confuse the issue. In my code, they have more descriptive names.
BCS