Home > Net >  Add list data to a dictionary
Add list data to a dictionary

Time:09-25

So I have a dictionary

dict={'Andrew':5, 'Brian':3, 'Clive':2, 'David':4}

it contains the names of volunteers and the number of times that they have volunteered for a particular duty. The dictionary is regularly updated by providing both the dictionary and a list to a function upd.

For the current update the following list has been declared - each name represents a new volunteer session:

ulist = ['Brian', 'David', 'Peter']

Write and demonstrate the function upd. Any ideas where to start

I have

def upd(lst):

I know its not much, but I am just learning about lists and dictionaries.

TIA

David.

EDIT:

My apologies, I should have been more specific

the upd function should create the dictionary and append/increment when a user is found, if not, it should create new user

CodePudding user response:

Here is what I imagine your requirements are:

If a name in ulist is already in the dictionary, increment the value associated with it, otherwise create an entry for the name and initialize the value to 1.

This code is quite simple really. Just iterate through each name in ulist and check to see if it is in my_dictionary, if not then add it, if so then increment it.

my_dictionary = {'Andrew':5, 'Brian':3, 'Clive':2, 'David':4}
ulist = ['Brian', 'David', 'Peter']

def udp(lst):
    for name in lst:
        if name in my_dictionary:
            my_dictionary[name]  = 1
        else:
            my_dictionary[name] = 1

udp(ulist)
print(my_dictionary)

Results:

{'Andrew': 5, 'Brian': 4, 'Clive': 2, 'David': 5, 'Peter': 1}

Note: You named your dictionary dict which is technically a keyword in Python so I recommend changing it to something like my_dictionary as shown in my example.

  • Related