简体   繁体   English

从Python中的字典中选择key:value对

[英]Select the key:value pairs from a dictionary in Python

I have a Python Dict like as follows: 我有一个Python Dict,如下所示:

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. 我想做的是从字典a中选择key:value对,并在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. 我可以简单地创建另一个字典,并使用带有迭代的key:value对对其进行更新,但是我遇到RAM问题,并且字典a很大。 b includes a few points so I thought popping from a does not work. b包含一些要点,所以我认为从a弹出不起作用。 What can I do to solve this issue? 我该怎么做才能解决这个问题?

Edit: Out is actually an update on a. 编辑:实际上是对a的更新。 So I will update the a as out. 所以我将更新为a。

Thanks :) 谢谢 :)

If you truly want to create a new dictionary with the keys in your list, then you can use a dict comprehension. 如果您确实想使用列表中的键来创建新字典,则可以使用dict理解。

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 . 这将通过提高故障KeyError ,如果任何的元素b实际上不在键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). 不会占用任何额外的空间 ,因为我们将所需的值从旧dict转移到了新dict,并且还解决了选择性弹出速度慢的问题(因为我们没有遍历所有对象,而只是遍历了需要)。

You could do this, 你可以这样

a = {"a":1,"b":2,"c":3,"f":4,"d":5}
b= ["b","c"]

out = {item:a.get(item)for item in b}

This won't raise any error, but adds '' if the item is not in a. 这不会引发任何错误,但是如果项目不在a中,则会添加''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM