How can I find the elements from a list in the keys from a dictionary?
I have created a dictionary and I am trying to find if the elements in a list called "seqrecord" are the keys of the dictionary. The script I have done is below:
def read_rebase(Renzymes):
renzymedict = {}
filenz = open(Renzymes)
for line in filenz.xreadlines():
fields = line.split()
name = fields[1]
pattern = fields[2]
renzymedict[(pattern)] = name
filenz.close()
return renzymedict
ren = {}
ren = read_rebase(Renzymes)
for k in seqrecord:
if k in ren:
print k, ren[k]
It doesn't work...
NameError: name 'ren' is not defined
What I am doing wrong? 'ren' should be the dictionary...
Thank you
• 4,609 views
•
link
2 answers
Use the built-in set functions of Python, eg:
s = set(seqrecord= ['a', 'b', 'd', 'e'])
m = set(myDict= {'a': 0, 'd': 0, 'f': 0})
s.intersection(m)
s.difference(m)
m.difference(s)
You do not have to transform them into sets before hand, of course. It can be done on the fly, just substitute s or m by set(...)
• 0 views
•
link
To intersect lists, i.e. to find what elements in a list are or are not present in another list, it is good to use list comprehensions, they are fast and readable:
seqrecord= ['a', 'b', 'd', 'e']
myDict= {'a': 0, 'd': 0, 'f': 0}
## Elements in common between seqrecord and keys
[x for x in seqrecord if x in myDict.keys()]
['a', 'd']
## Elements in seqrecord NOT in keys
[x for x in seqrecord if x not in myDict.keys()]
['b', 'e']
## Keys NOT in seqrecord
[x for x in myDict.keys() if x not in seqrecord]
['f']
• 0 views
•
link
Log in to answer this question.
after a
returnstatement nothing will be executed! the function returns to its call by returningrenzymedictI have deleted return statement, but the result is the same (
'ren' is not defined)Maybe your indentation is wrong in your posted code?
try this
I don't think so,
are "inside" the
def read_basefunction...but this will not work. if you put it outside of the function it will work. it works like this:
now ren is declared and a known variable which can be used in
Ok, modified this error, now there is a new one...
(Thank you for your answers)
Renzymes is variable which should contain your filename.
Sorry, I don't understand what I should do
Here is how you defined your function
read_rebase:When you call this function, you need to provide some value for the local variable
Renzymesthat is a path to a file somewhere. For example:The file
/your/path/and/file.txtwill get opened in the functionread_rebase.If you instead call this function like so:
Then you need to have defined a global variable (also poorly and ambiguously named as
Renzymes) somewhere further up in the code. If this variable is not defined, then theread_rebasefunction cannot work.So either set the path to the file explicitly, as shown above, or set a sensibly-named variable and pass that to your function, e.g.:
Thank you so much! It works! :)