我有以下命令:
abc = {"type":"insecure","id":"1","name":"peter"}
Run Code Online (Sandbox Code Playgroud)
我想做的是基于旧字典创建一个新字典,其中没有键“type”,键“id”更改为“identity”。新的字典将如下所示:
xyz = {"identity":"1","name":"peter"}
Run Code Online (Sandbox Code Playgroud)
我想出的解决方案如下:
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"]
Run Code Online (Sandbox Code Playgroud)
我想知道这是否是最快且有效的方法?目前,“abc”只有三个值。如果“abc”更大并且有很多值,那么我的解决方案仍然高效且快速。
无论如何你想创建一本新字典。您可以在字典理解中迭代键/值,这更紧凑,但功能相同:
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"]
Run Code Online (Sandbox Code Playgroud)
您可以使用字典理解:
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
Run Code Online (Sandbox Code Playgroud)
输出:
{'name': 'peter', 'identity': '1'}
Run Code Online (Sandbox Code Playgroud)
无需迭代原始字典:
abc = {"type":"insecure","id":"1","name":"peter"}
xyz = abc.copy()
xyz.pop('type')
xyz['identity'] = xyz.pop('id')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16668 次 |
| 最近记录: |