Home > Software design >  Create dictionary with dynamic values in python
Create dictionary with dynamic values in python

Time:09-22

I want to create python dictionary something like below {"Disk1" : "deva", "Disk2" :"devb" , "Disk3": "devc" .....}

How can I create the above dictionary without defining all vales statically

CodePudding user response:

You can create an empty dictionary and add the keys/values later:

my_dict = {}

key = "abc"
value = 123

my_dict[key] = value

CodePudding user response:

Do the following :

def disck():
    g = {}
    for i in range(1,27):
        f = 'Disck' str(i)
        j = 'dev'  chr(97 i-1)
        g.update({f:j})
    return g

CodePudding user response:

If you know the keys in advance, it can be done as:

from collections import defaultdict
def add_to_dict(key, value, dict):
    dict[key] = value
    
out = defaultdict(str)
out['Disk1'] = ''
out['Disk2'] = ''
add_to_dict('Disk1', 'deva', out)
add_to_dict('Disk2', 'devb', out)
print (out)

Output:

defaultdict(<class 'str'>, {'Disk1': 'deva', 'Disk2': 'devb'})
  • Related