2

我有以下字典:

abc = {"type":"insecure","id":"1","name":"peter"}

我想要做的是有一个基于旧字典的新字典,其中没有键“类型”,键“id”更改为“身份”。新的 dict 将如下所示:

xyz = {"identity":"1","name":"peter"}

我想出的解决方案如下:

abc = {"type":"insecure","id":"1","name":"peter"}
xyz = {}
black_list_values = set(("type","id"))
for k in abc:
    if k not in blacklist_values:
        xyz[k] = abc[k]
xyz["identity"] = abc["id"]

我想知道它是否是最快和最有效的方法?现在,“abc”只有三个值。如果“abc”更大并且有很多值,那么我的解决方案仍然是高效和快速的。

4

5 回答 5

6

无论如何,您都想创建一个新字典。您可以在字典理解中迭代键/值,这更紧凑,但功能相同:

abc = {"type":"insecure","id":"1","name":"peter"}

black_list_values = set(("type","id"))

xyz = {k:v for k,v in abc.iteritems() if k not in black_list_values}
xyz["identity"] = abc["id"]
于 2013-05-10T10:40:35.973 回答
6

您可以使用字典理解:

abc = {"type":"insecure","id":"1","name":"peter"}
black_list = {"type"}
rename ={"id":"identity"}  #use a mapping dictionary in case you want to rename multiple items
dic = {rename.get(key,key) : val for key ,val in abc.items() if key not in black_list}
print dic

输出:

{'name': 'peter', 'identity': '1'}
于 2013-05-10T10:43:47.843 回答
3

无需遍历原始字典:

abc = {"type":"insecure","id":"1","name":"peter"}
xyz = abc.copy()
xyz.pop('type')
xyz['identity'] = xyz.pop('id')
于 2013-05-10T10:57:39.030 回答
2

如果所有的键都是预先知道的并且它是一个简短的键列表,那么显而易见的解决方案就是

xyz = {"identity":abc["id"],"name":abc["name"]}
于 2015-10-02T14:26:40.760 回答
1

另一个简单的建议是使用该dict()功能:

abc = {"type":"insecure","id":"1","name":"peter"}
xyz = dict(abc)

然后以您认为合适的任何方式执行替换 =-)

于 2017-11-30T15:07:14.260 回答