Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 570
Alex Gordon Avatar asked Aug 05 '10 21:08

Alex Gordon


People also ask

How do you append to a list that is a value in a dictionary Python?

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]} ”.

How do I add multiple values to a dictionary?

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.


2 Answers

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'] 
like image 195
Tony Veijalainen Avatar answered Sep 19 '22 04:09

Tony Veijalainen


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'] 
like image 24
Piotr Czapla Avatar answered Sep 22 '22 04:09

Piotr Czapla