Home > front end >  dict get item from key
dict get item from key

Time:03-15

I'm trying to get a key-value item from a dictionary using a key instead of getting only the value. I understand that I could do something like

foo = {"bar":"baz", "hello":"world"}
some_item = {"bar": foo.get("bar")}

But here I need to type out the key twice, which seems a bit redundant. Is there some direct way to get the key-value pair for the key bar? Something like

foo.get_item("bar")
>>> {"bar": "baz"}

CodePudding user response:

One way or another, you'll need to bind "bar" to a variable.

>>> foo = {"bar":"baz", "hello":"world"}
>>> (lambda k="bar": {k: foo[k]})()
{'bar': 'baz'}

or:

>>> k = "bar"
>>> {k: foo[k]}
{'bar': 'baz'}

or:

>>> def item(d, k):
...     return {k: d[k]}
...
>>> item(foo, "bar")
{'bar': 'baz'}

CodePudding user response:

It's possible to extend dict to create your own methods. It could be useful if you're the one creating the initial dictionary in the first place.

class MyDict(dict):
    def fetch(self, key):
        return {key:self.get(key)}

The downside is you would need to recast regular dictionaries (assuming you didn't create the initial)

new_foo = MyDict(foo)
some_item = new_foo.fetch("bar")

But in this case it would probably be easier just to use a lambda (see Samwise's answer)

CodePudding user response:

you can get the key value pair for key 'bar' by doing something like ->

foo = {"bar":"baz", "hello":"world"}
some_item = {k:v for k,v in foo.items() if k=='bar'}
  • Related