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'
.
By using ” + ” operator we can append the lists of each key inside a dictionary in Python. After writing the above code (Python append to the lists of each key inside a dictionary), Ones you will print “myvalue” then the output will appear as a “ {'Akash': [1, 3], 'Bharat': [4, 6]} ”.
By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With