简体   繁体   中英

How to search key from key-value pair in python

I have written code that is creating key-value pairs of a file from my computer and storing them in a list a . This is the code:

groups = defaultdict(list)
with open(r'/home/path....file.txt') as f:
    lines=f.readlines()
    lines=''.join(lines)
    lines=lines.split()
    a=[]
    for i in lines:
        match=re.match(r"([a,b,g,f,m,n,s,x,y,z]+)([-+]?[0-9]*\.?[0-9]+)",i,re.I)
        if match:
            a.append(match.groups())
print a

Now I want to find if a particular key is in that list or not. For example, my code generates this output:

[('X', '-6.511'),('Y', '-40.862'), 
('X', '-89.926'),('N', '7304'),
('X', '-6.272'), ('Y', '-40.868'), 
('X', '-89.979'),('N', '7305'),
('Y', '-42.101'),('Z', '238.517'),
('N', '7306'),   ('Y','-43.334'), 
('Z', '243.363'),('N', '7307')]

Now,in output the keys are 'X' , 'Y' , 'Z' , 'N' But the keys I'm looking for are A , B , G , F , M , N , S , X , Y , Z . So for those keys, that are not in output, the output should display something like "A not in list" , "B not in list" .

for node in ['A', 'B', 'G', 'F', 'M', 'N', 'S', 'X', 'Y', 'Z']:
    if node not in groups.keys():
        print "%s not in list"%(node)

use a variable and a print function as you iterate through the list

I think this is what you want.

You can read your tuples list as dict and check for key existence:

d=[('X', '-6.511'),('Y', '-40.862'), 
('X', '-89.926'),('N', '7304'),
('X', '-6.272'), ('Y', '-40.868'), 
('X', '-89.979'),('N', '7305'),
('Y', '-42.101'),('Z', '238.517'),
('N', '7306'),   ('Y','-43.334'), 
('Z', '243.363'),('N', '7307')]

k=['A', 'B', 'G', 'F', 'M', 'N', 'S', 'X', 'Y', 'Z']
dt=dict(d)
for i in k:
    if i in dt:
        print i," has found"
    else:
        print i," has not found"

Output:

A  has not found
B  has not found
G  has not found
F  has not found
M  has not found
N  has found
S  has not found
X  has found
Y  has found
Z  has found
mylist = [('X', '-6.511'),('Y', '-40.862'), 
('X', '-89.926'),('N', '7304'),
('X', '-6.272'), ('Y', '-40.868'), 
('X', '-89.979'),('N', '7305'),
('Y', '-42.101'),('Z', '238.517'),
('N', '7306'),   ('Y','-43.334'), 
('Z', '243.363'),('N', '7307')]

missing = [ x for x in 'ABGFMNSXYZ' if x not in set(v[0] for v in mylist) ]
for m in missing:
    print "{} not in list".format(m)

Gives:

A not in list
B not in list
G not in list
F not in list
M not in list
S not in list
if ('X', '-6.511') in mylist:
   print('Yes')
else:
   print('No')

Use List or Numpy array for mylist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM