I am have the following dict:
abc = {"type":"insecure","id":"1","name":"peter"}
what I want to do is to have a new dict based on the old dict in which there is no key "type" and key "id" is changed to "identity". The new dict will look as follows:
xyz = {"identity":"1","name":"peter"}
The solution that I came up was as follows:
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"]
I was wondering if its the fastest and efficient way to do that? Right now, "abc" have only three values. If "abc" is much bigger and have many values then is my solution still the efficient and fast.
You want to create a new dictionary anyway. You can iterate over keys/values in a dict comprehension, which is more compact, but functionally the same:
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With