python: print values from a dictionary - python

generic_drugs_mapping={'MORPHINE':[86],
'OXYCODONE':[87],
'OXYMORPHONE':[99],
'METHADONE':[82],
'BUPRENORPHINE':[28],
'HYDROMORPHONE':[54],
'CODEINE':[37],
'HYDROCODONE':[55]}
How do I return 86?
This does not seem to work:
print generic_drugs_mapping['MORPHINE'[0]]

You have a bracket in the wrong place:
print generic_drugs_mapping['MORPHINE'][0]
Your code is indexing the string 'MORPHINE', so it's equivalent to
print generic_drugs_mapping['M']
Since 'M' is not a key in your dictionary, you won't get the results you expect.

The list is the value stored under the key. The part that gets the value out is generic_drugs_mapping['MORPHINE'] so this has the value [86]. Try moving the index outside like this :
generic_drugs_mapping['MORPHINE'][0]

Related

Slicing a dictionary's value isn't working properly

So I have a json file which contains role ids (a dictionary named roles),with a key (which is the name of the role) and each key has the role's id as it's value
Looks something like this:
{"Ban": ["694175790639743076"], "Muted": ["692863646543380590"]}
I mostly just need the ids from the json
using something like roles['Muted'] or roles.get('Muted') gives me ['692863646543380590']:
Muted=roles.get('Muted')
print(Muted)
the functions take integers,so I have to remove [' from the output and get this: 692863646543380590
slicing just gives me [] no matter what slicing I use:
work=boost1[2:20] *or any other slice*
print(work)
gives out "[]"
why is slicing just not working here? and how do I fix this??
first of all roles['Muted'] is a list, if you want just first element then get it with 0 index then try using int() for converting it to Integer:
Muted=int(roles.get('Muted')[0]) # or Muted=int(roles['Muted'][0])
Muted will be:
692863646543380590
Try this -
work = int(boost1[0]) #fetching the first element of list and converting it into int

Python: print the dictionary elements which has multiple values assigned for each key

I've got a dictionary like the one, below:
{ "amplifier": ["t_audio"],
"airbag": ["t_trigger"],
"trigger": ["t_sensor1", "t_sensor2"],
"hu": ["t_fused"],
"cam": ["t_front", "t_ldw", "t_left", "t_nivi", "t_rear_camera", "t_right"],
"video_screen": ["t_video"] }
as you can see, there are some elements which have more than one value assigned for each key. I'd like to extract those values as string, separately within (preferably) a for loop then print them out. Printed result should be something like this:
group(amplifier, t_audio)
group(airbag, t_trigger)
group(trigger, t_sensor1)
group(trigger, t_sensor2)
group(hu, t_fused)
group(cam, t_front)
group(cam, t_ldw)
...
...
I can easily perform this on a normal dictionary where each key has only one values but got almost confused about this one(sorry if I'm newbe to Python...). Any kind of help is appreciated on how to get this result.
Very simple: loop through each key in the dictionary. Since each value is going to be a list with one or more elements, just loop through those and print the string you need:
d = {'amplifier': ['t_audio'], 'hu': ['t_fused'], 'trigger': ['t_sensor1', 't_sensor2'], 'cam': ['t_front', 't_ldw', 't_left', 't_nivi', 't_rear_camera', 't_right'], 'airbag': ['t_trigger'], 'video_screen': ['t_video']}
for key in d:
for value in d[key]:
print 'group({},{})'.format(key,value)
You can see it in action here: https://eval.in/645071
for key in dict:
for value in dict[key]:
print value
for k, v in mydict.iteritems():
for vv in v:
print "group(%s,%s)" % (k,vv)
#or
print "group(",k,",",vv,")"
#or the python 3 format syntax

Python Dictionary -index numbering is different every time

I'm using python 2.7\ Linux
I have api result (see below):
{"id":"137","iv":0,
"components":[{"id":"928","type":"IDUGW","creation_date":"2016-05-04 08:10:38.0","update_date":"2016-05-04 08:10:38.0","unit_id":"137","serial_number":"00000000501C8349"},
{"id":"927","type":"IDU","creation_date":"2016-05-04 08:10:37.0","update_date":"2016-05-04 08:10:37.0","unit_id":"137","serial_number":"00000000501C8268"},
{"id":"930","type":"Battery","creation_date":"2016-05-04 08:10:40.0","update_date":"2016-05-04 08:10:40.0","unit_id":"137","serial_number":"00000000501C802A"}
,{"id":"929","type":"Panel","creation_date":"2016-05-04 08:10:39.0","update_date":"2016-05-04 08:10:39.0","unit_id":"137","serial_number":"00000000501C810B"}],
"creation_date":"2016-05-04 08:10:41.0",
"update_date":"2016-05-04 08:10:41.0",
"serial_number":"0011",
"phone_number":"972528745028",
"owner_phone":"9720545555554"}
if i understand it right, i have dictionary inside dictionary ( 2nd line "component" is another dictionary which has 4 key\values in it)
I'm trying to check if in dictionary the "type" equals to parameter i give.
Code:
if (MyDictionary[u'components'][0][u'type'] <> lRestParams['type4']):
i have 4 index (0,1,2,3)
sometimes the "if" pass, and sometimes the index is changed (when rebuilding everything) and it fails
how can i compare type4 to MyDictionary[u'components'][one of index][u'type']
In addition i need to compare after that that the value of the key = value4
so it means that if we check index x than key and value should be checked there.
Hope not to complicated
Thanks in advance
Ohad
Instead of giving the index number, you can loop through the component values to do the comparision.
for keys in data['components']:
if keys['type'] == "IDUGW":
print "matched"

Getting a strange result when comparing 2 dictionaries in python

So I have a pair of dictionaries in python: (both have exactly the same keys)
defaults = {'ToAlpha': 4, 'ToRed': 4, 'ToGreen': 4, 'ToBlue': 4,}
bridged = {'ToAlpha': 3, 'ToRed': 0, 'ToGreen': 1, 'ToBlue': 2,}
When I iterate through one of the dictionaries I do a quick check to see if the other dict has the same key, if it does then print it.
for key, value in defaults.iteritems():
if bridged.get(key):
print key
What I would expect to see is:
ToAlpha
ToRed
ToGreen
ToBlue
But for some reason, 'ToRed' is not printed. I must be missing something really simple here, but have no idea might might be causing this.
bridged.get('ToRed')
and
defaults.get('ToRed')
both work independently, but when iterated through the loop... Nothing!
Any idea's?
0 is false. Use in to check for containment.
if key in bridged:
The problem is in the if statement when 'ToRed' gets passed.
if 0
returns false, so the key is not returned. Use
if key in bridged
The problem is when key is ToRed, then bridged.get('ToRed') will be 0.
So following will evaluate to False:
if bridged.get(key):
thereby not printing 'ToRed'.
Instead of this, use the in operator.
Using in the most pythonic way to check if a key is in a dictionary.
So check using this:
if key in bridged:
Final code now becomes:
>>> for key, value in defaults.iteritems():
if key in bridged:
print key
ToAlpha
ToRed
ToBlue
ToGreen

eliminate '\n' in dictionary

I have a dictionary looks like this, the DNA is the keys and quality value is value:
{'TTTGTTCTTTTTGTAATGGGGCCAGATGTCACTCATTCCACATGTAGTATCCAGATTGAAATGAAATGAGGTAGAACTGACCCAGGCTGGACAAGGAAGG\n':
'eeeecdddddaaa`]eceeeddY\\cQ]V[F\\\\TZT_b^[^]Z_Z]ac_ccd^\\dcbc\\TaYcbTTZSb]Y]X_bZ\\a^^\\S[T\\aaacccBBBBBBBBBB\n',
'ACTTATATTATGTTGACACTCAAAAATTTCAGAATTTGGAGTATTTTGAATTTCAGATTTTCTGATTAGGGATGTACCTGTACTTTTTTTTTTTTTTTTT\n':
'dddddd\\cdddcdddcYdddd`d`dcd^dccdT`cddddddd^dddddddddd^ddadddadcd\\cda`Y`Y`b`````adcddd`ddd_dddadW`db_\n',
'CTGCCAGCACGCTGTCACCTCTCAATAACAGTGAGTGTAATGGCCATACTCTTGATTTGGTTTTTGCCTTATGAATCAGTGGCTAAAAATATTATTTAAT\n':
'deeee`bbcddddad\\bbbbeee\\ecYZcc^dd^ddd\\\\`]``L`ccabaVJ`MZ^aaYMbbb__PYWY]RWNUUab`Y`BBBBBBBBBBBBBBBBBBBB\n'}
I want to write a function so that if I query a DNA sequence, it returns a tuple of this DNA sequence and its corresponding quality value
I wrote the following function, but it gives me an error message that says list indices must be integers, not str
def query_sequence_id(self, dna_seq=''):
"""Overrides the query_sequence_id so that it optionally returns both the sequence and the quality values.
If DNA sequence does not exist in the class, return a string error message"""
list_dna = []
for t in self.__fastqdict.keys():
list_dna.append(t.rstrip('\n'))
self.dna_seq = dna_seq
if self.dna_seq in list_dna:
return (self.dna_seq,self.__fastqdict.values()[self.dna_seq + "\n"])
else:
return "This DNA sequence does not exist"
so I want something like if I print
query_sequence_id("TTTGTTCTTTTTGTAATGGGGCCAGATGTCACTCATTCCACATGTAGTATCCAGATTGAAATGAAATGAGGTAGAACTGACCCAGGCTGGACAAGGAAGG"),
I would get
('TTTGTTCTTTTTGTAATGGGGCCAGATGTCACTCATTCCACATGTAGTATCCAGATTGAAATGAAATGAGGTAGAACTGACCCAGGCTGGACAAGGAAGG',
'eeeecdddddaaa`]eceeeddY\\cQ]V[F\\\\TZT_b^[^]Z_Z]ac_ccd^\\dcbc\\TaYcbTTZSb]Y]X_bZ\\a^^\\S[T\\aaacccBBBBBBBBBB')
I want to get rid of "\n" for both keys and values, but my code failed. Can anyone help me fix my code?
The newline characters aren't your problem, though they are messy. You're trying to index the view returned by dict.values() based on the string. That's not only not what you want, but it also defeats the whole purpose of using the dictionary in the first place. Views are iterables, not mappings like dicts are. Just look up the value in the dictionary, the normal way:
return (self.dna_seq, self.__fastqdict[self.dna_seq + "\n"])
As for the newlines, why not just take them out when you build the dictionary in the first place?
To modify the dictionary you can just do the following:
myNewDict = {}
for var in myDict:
myNewDict[var.strip()] = myDict[var].strip()
You can remove those pesky newlines from your dictionary's keys and values like this (assuming your dictionary was stored in a variable nameddna):
dna = {k.rstrip(): v.rstrip() for k, v in dna.iteritems()}

Categories

Resources