[英]dict get item from key
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.但是这里我需要敲两次key,显得有点多余。 Is there some direct way to get the key-value pair for the key
bar
?有没有一些直接的方法来获取键
bar
的键值对? Something like就像是
foo.get_item("bar")
>>> {"bar": "baz"}
One way or another, you'll need to bind "bar"
to a variable.不管怎样,您需要将
"bar"
绑定到一个变量。
>>> 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'}
It's possible to extend dict
to create your own methods.可以扩展
dict
来创建你自己的方法。 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 )但在这种情况下,使用 lambda 可能会更容易(参见Samwise 的回答)
you can get the key value pair for key 'bar' by doing something like ->您可以通过执行类似 -> 的操作来获取键“bar”的键值对
foo = {"bar":"baz", "hello":"world"}
some_item = {k:v for k,v in foo.items() if k=='bar'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.