Home > Mobile >  How to add dict value from a list of value python
How to add dict value from a list of value python

Time:11-22

i have a code like this :

values = [1, 'admin', 'admin123']
dict   = {'id':'', 'username':'', 'password':''}
 

i want to make it like this :

{
    'id': 1,
    'username': 'admin'
    'password': 'admin123'
}

but with for loop. not manually like :

{
    'id': values[0],
    'username': values[1],
    'password': values[2]  
}

how?

CodePudding user response:

You can use the dict.Keys() method to get a list of all the keys. Then you can loop over them and assing values to those keys in your dictionary

CodePudding user response:

I think you need something like this

values = [1, 'admin', 'admin123']
dict = {'id': '', 'username': '', 'password': ''}


for k, v in zip(dict, values):
    dict[k] = v

print(dict)

  • Related