[英]python dict of lists
I have following dict: 我有以下意见:
items_temp = dict(fruits=["apple", "orange"], vegetables=["carrot", "potato"], animals=["dog", "cat"])
and following list to be verified what kind of things it contains. 以及下面要验证的列表中包含的东西。
check = ["orange", "dog", "apple"]
is there any clever pythonic way to obtain following dict from data above?: 有什么聪明的pythonic方式可以从上面的数据中获得以下命令?
output = dict(fruits = ["orange", "apple"], animals=["dog"])
I think you should be able to do the following: 我认为您应该能够执行以下操作:
check = set(['orange', 'dog', 'apple'])
output = {k: check.intersection(v) for k, v in items_temp.items() if check.intersection(v)}
Basically, I'm checking the intersection between check
and the values of your dictionary. 基本上,我正在检查
check
和字典值之间的交集。 If there is an intersection, we add it to the output. 如果有一个路口,我们把它添加到输出。
This will give you a dictionary with sets as values, but you can convert that pretty easily. 这将为您提供一个以集合为值的字典,但是您可以很轻松地进行转换。
Note that we're doing the intersection check twice. 请注意,我们要进行两次相交检查。 That's a bit annoying (and we definitely don't need to) if we add an extra step into the processing pipeline...
如果我们在处理管道中增加一个额外的步骤,那会有点烦人(而且我们绝对不需要)。
check = set(['orange', 'dog', 'apple'])
keys_intersect = ((k, check.intersection(v)) for k, v in items_temp.iteritems())
output = {k: intersect for k, intersect in keys_intersect if intersect}
There isn't a clean, single step way to get what you want, but you can do it in two: 没有一种简单的单步方式即可获得所需的东西,但是您可以分两步进行:
>>> output = {k:[v for v in vs if v in check] for k,vs in items_temp.items()}
>>> output
{'vegetables': [], 'animals': ['dog'], 'fruits': ['apple', 'orange']}
Next, we just need to filter out the empty lists: 接下来,我们只需要过滤掉空列表:
>>> output = {k:vs for k,vs in output.items() if vs}
>>> output
{'animals': ['dog'], 'fruits': ['apple', 'orange']}
If you've got a lot of items to check, you can speed things up considerably by turning check
into a set
, but premature optimization is the root of all evil . 如果您要检查的物品很多,则可以通过将
check
变成一set
来显着提高速度,但是过早的优化是万恶之源 。
Edit: I suppose you can do it in one: 编辑:我想你可以做到之一:
>>> output = {k:[v for v in vs if v in check] for k,vs in items_temp.items() if any(v in check for v in vs)}
>>> output
{'animals': ['dog'], 'fruits': ['apple', 'orange']}
But that's over-complicating things with redundant testing. 但这会使冗余测试变得过于复杂。
You could also do 你也可以
{k:vs for k,vs in ((k,[v for v in vs if v in check]) for k,vs in items_temp.items()) if vs}
To do it in one step without redundant membership checking, but now we're getting a little silly. 一步来完成此操作而无需进行冗余的成员资格检查,但是现在我们有点傻了。
Why don't you use a dictionary? 你为什么不使用字典?
a={"Mobin":"Iranian","Harry":"American"}
and you can get that with this: 你可以用这个来实现:
print a.get("Mobin")
when you run this code,you can see 'Iranian' in screen 运行此代码时,您可以在屏幕上看到“伊朗语”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.