Appending values to dictionary in Python

I have a dictionary to which I want to append to each drug, a list of numbers. Like this:

append(0), append(1234), append(123), etc.

def make_drug_dictionary(data):
    drug_dictionary={'MORPHINE':[],
                     'OXYCODONE':[],
                     'OXYMORPHONE':[],
                     'METHADONE':[],
                     'BUPRENORPHINE':[],
                     'HYDROMORPHONE':[],
                     'CODEINE':[],
                     'HYDROCODONE':[]}
    prev = None
    for row in data:
        if prev is None or prev==row[11]:
            drug_dictionary.append[row[11][]
    return drug_dictionary

I later want to be able to access the entirr set of entries in, for example, 'MORPHINE'.

  1. How do I append a number into the drug_dictionary?
  2. How do I later traverse through each entry?

Solution 1:

Just use append:

list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']

Solution 2:

You should use append to add to the list. But also here are few code tips:

I would use dict.setdefault or defaultdict to avoid having to specify the empty list in the dictionary definition.

If you use prev to to filter out duplicated values you can simplfy the code using groupby from itertools Your code with the amendments looks as follows:

import itertools
def make_drug_dictionary(data):
    drug_dictionary = {}
    for key, row in itertools.groupby(data, lambda x: x[11]):
        drug_dictionary.setdefault(key,[]).append(row[?])
    return drug_dictionary

If you don't know how groupby works just check this example:

>>> list(key for key, val in itertools.groupby('aaabbccddeefaa'))
['a', 'b', 'c', 'd', 'e', 'f', 'a']

Solution 3:

It sounds as if you are trying to setup a list of lists as each value in the dictionary. Your initial value for each drug in the dict is []. So assuming that you have list1 that you want to append to the list for 'MORPHINE' you should do:

drug_dictionary['MORPHINE'].append(list1)

You can then access the various lists in the way that you want as drug_dictionary['MORPHINE'][0] etc.

To traverse the lists stored against key you would do:

for listx in drug_dictionary['MORPHINE'] :
  do stuff on listx

Solution 4:

To append entries to the table:

for row in data:
    name = ???     # figure out the name of the drug
    number = ???   # figure out the number you want to append
    drug_dictionary[name].append(number)

To loop through the data:

for name, numbers in drug_dictionary.items():
    print name, numbers