Skip to content Skip to sidebar Skip to footer

How To Put Values Of A Given List Into A Existing Dictionary?

I've got a List with their elements my_list = ['a', 'b', 'c'] and a Dictionary that has their keys and blank strings as their values my_dictionary = { 'key_a' : '', 'key_b

Solution 1:

You can try this.

dict(zip(my_dictionary,my_list))

Use .update method to update your my_dictionary.


Output

{'key_a': 'a', 'key_b': 'b', 'key_c': 'c'}

Note: This works for python3.7 or above.

The reason is stated in the comments by @MisterMiyagi.

Solution 2:

I assume that your dictionary order is guaranteed or you don't care the order. You can use built-in function zip. It is very useful function to iterate two different iterables. documentation: https://docs.python.org/3/library/functions.html#zip

my_dictionary = {
    'key_a': '',
    'key_b': '',
    'key_c': '',
}

my_list = ['a', 'b', 'c']

for key, item inzip(my_dictionary, my_list):
    my_dictionary[key] = item

print(my_dictionary)

output: {'key_a': 'a', 'key_b': 'b', 'key_c': 'c'}

Solution 3:

Try this :

i = 0forkeyin my_dict:
      my_dict[key] = my_list[i]
      i+=1

Output : {'key_a': 'a', 'key_b': 'b', 'key_c': 'c'}

Solution 4:

You can try this:

my_list = ['a', 'b', 'c']

my_dict = {
    'key_a' : '',
    'key_b' : '',
    'key_c' : '',
}

forindex, key in enumerate(my_dict):
    my_dict[key] = my_list[index]

print(my_dict)

Post a Comment for "How To Put Values Of A Given List Into A Existing Dictionary?"