hjelpmig hjelpmig - 7 months ago 31
Python Question

create a new dict based on old dict

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 can use a dict-comprehension:

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'}