python - create a new dict based on old dict -
i have following dict:
abc = {"type":"insecure","id":"1","name":"peter"}
what want have new dict based on old dict in there no key "type" , key "id" changed "identity". new dict follows:
xyz = {"identity":"1","name":"peter"}
the solution came follows:
abc = {"type":"insecure","id":"1","name":"peter"} xyz = {} black_list_values = set(("type","id")) k in abc: if k not in blacklist_values: xyz[k] = abc[k] xyz["identity"] = abc["id"]
i wondering if fastest , efficient way that? right now, "abc" have 3 values. if "abc" bigger , have many values solution still efficient , fast.
you can use dict-comprehension:
abc = {"type":"insecure","id":"1","name":"peter"} black_list = {"type"} rename ={"id":"identity"} #use mapping dictionary in case want rename multiple items dic = {rename.get(key,key) : val key ,val in abc.items() if key not in black_list} print dic
output:
{'name': 'peter', 'identity': '1'}
Comments
Post a Comment