Home > Software design >  Create New Dictionary based on Existing Dictionary matching a variable with Keys in Existing Diction
Create New Dictionary based on Existing Dictionary matching a variable with Keys in Existing Diction

Time:10-11

I have dictionary dicts. I have variable ID = "gateway_id". I want to create new dictionary dicts2 of containing key, value pair match with variable ID.

Code:

dicts = {'gateway_id':"123","hi":"hello"}

ID = 'gateway_id'

New Dict: Expected Output

dicts2 = {'gateway_id':"123"}

CodePudding user response:

Simply:

dicts = {'gateway_id':"123","hi":"hello"}
ID = 'gateway_id' # id is a python builtin

dicts2 = {ID: dicts[ID]}

output: {'gateway_id': '123'}

  • Related