Reputation: 69
I need to reconstruct a new dictionary based on the keys present in an array.from an existing dictionary. array value will be changing each and every time
olddict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"createdby": "Mustang",
"orderedby": "Mustang"
}
arr = ['brand','year','createdby']
Required output :
newdict= {
"brand": "Ford",
"year": 1964,
"createdby": "Mustang"
}
Upvotes: 0
Views: 158
Reputation: 23
you can use Dictionary Comprehension technique.
newdict = {key:olddict[key] for key in arr}
where key
is everything in arr
list/array and value of newdict
is olddict[key]
.
Hope you find it easy and useful <3
Upvotes: 1
Reputation: 1
You can add this function:
def updated_dict(arr, olddict):
newdict = {}
for item in arr:
newdict[item] = olddict.get(item)
return newdict
Upvotes: 0
Reputation: 632
olddict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"createdby": "Mustang",
"orderedby": "Mustang"
}
arr = ['brand','year','createdby']
newdict = {}
for key in arr:
# key = 'brand'
newdict[key] = olddict[key] # newdict['brand'] = olddict['brand']
newdict = {
"brand": "Ford",
"year": 1964,
"createdby": "Mustang"
}
Upvotes: 0
Reputation: 605
Try to use below code:
newdict = {param:olddict.get(param) for param in arr}
Upvotes: 0