Chirsty CR_007
Chirsty CR_007

Reputation: 69

Python - Pushing values present in a array to Dictionary

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

Answers (4)

Syed Fasih
Syed Fasih

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

or bar zur
or bar zur

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

devspartan
devspartan

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

Astik Gabani
Astik Gabani

Reputation: 605

Try to use below code:

newdict = {param:olddict.get(param) for param in arr}

Upvotes: 0

Related Questions