Home > Mobile >  Adding to a dictionary based on key and value from lists?
Adding to a dictionary based on key and value from lists?

Time:10-13

I have a dictionary defined as:

letters = {'a': 2, 'b': 1, 'c': 5}

I want to add values to this dictionary based on two lists: one which contains the keys and another which contains the values.

key_list = [a, c]
value_list = [2, 5]

This should give the output:

{a: 4, b: 1, c: 10}

Any ideas on how I can accomplish this? I am new to working with the dictionary structure so I apologise if this is extremely simple.

Thanks.

CodePudding user response:

You can zip the two lists and then add to the dictionary as so;

letters = {'a': 2, 'b': 1, 'c': 5}

key_list = ['a', 'c']
value_list = [2, 5]

for k,v in zip(key_list, value_list):
    letters[k] = letters.get(k, 0)   v

Using the dictionary's get() method as above allows you to add letters that aren't already in the dictionary.

CodePudding user response:

for i in range(len(key_list)):
    letters[key_list[i]]  = value_list[i]

CodePudding user response:

You can simply add or modify values from a dictionary using the key For example:

letters = {'a': 2, 'b':1 , 'c': 5}

letters['a']  = 2
letters['c']  = 5

print(letters)

output = {'a': 4, 'b': 1, 'c': 10}

  • Related