Reputation: 1644
I'm trying to make a dictionary with values 'True' or 'False' when comparing elements in 2 lists. This is probably a bit basic but I'm new to coding and I don't understand why it always assigns the 'True' value even though I can see its not true:
letters = [A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z]
randomData = []
f = open('randomData.txt', 'r')
for line in f:
randomData.append(line.rstrip().split()[0])
f.close()
The 'randomData.txt' file looks like:
A'\t'0003'\t'0025'\t'chr1
B'\t'0011'\t'0021'\t'chr7
D'\t'0043'\t'0068'\t'chr3
F'\t'0101'\t'0119'\t'chr7
The randomData list should now look like:
['A','B','D','F']
I tried:
sameLetters = {}
i=0
while i < len(letters):
if letters[i] and randomData:
#append to dictionary
sameLetters[letters[i]] = 'True'
else:
#append to dictionary
sameLetters[letters[i]] = 'False'
i=i+1
print sameLetters
I expected something like:
{'A': 'True', 'B': 'True', 'C': 'False', 'D': 'True', 'E': 'False', 'F': 'True', 'G': 'False', etc
Instead all values in the dictionary are 'True'. Can anyone see the problem? Or give any pointers or explanations? Any help would be great, many thanks.
Upvotes: 1
Views: 271
Reputation: 9749
Seems like you only care about which letter appears in your random data, so why not use a set
?
from string import ascii_uppercase
randomData = ['A', 'B', 'D', 'F', 'A']
appeared = set(ascii_uppercase).intersection(set(randomData))
print appeared
And later you can us it like this:
char = 'z'
if char in appeared:
print 'yes'
else:
print 'no'
EDIT:
Then how about this:)
from string import ascii_uppercase
randomData = ['A', 'B', 'D', 'F', 'A']
appeared = set(ascii_uppercase).intersection(set(randomData))
d = dict(zip(ascii_uppercase, (False,) * 26))
for key in appeared:
d[key] = True
print d
Upvotes: 0
Reputation: 122115
I think you want to do something like:
sameLetters = {l: l in randomData for l in letters}
Your current attempt doesn't work because you check
if letters[i] and randomData:
# ^ should be in
and Python interprets both non-empty strings (letters[i]
) and non-empty lists (randomData
) as True.
Also, note that letters
is already available in Python:
from string import ascii_uppercase
This is a string, but you can iterate through and index a string just like a list, and in
will still work.
Upvotes: 1