On Tue, Jul 22, 2014 at 01:10:18PM +0200, jarod...@libero.it wrote:

> But I havethis problem I have a file and I want to know which elements are 
> not 
> present on my file from dictionary.
>  more data.tmp 
> jack  1
> pippo 1
> luis  1
> frate 1
> livio 1
> frank 1
> 
> 
> with open("data.tmp") as p:
>     for i in p:
>         lines= i.strip("\n").split("\t")
>         if not diz.has_key(lines[0]):
>    ....:             print i
>    ....:             
> pippo 1
> luis  1
> frate 1
> livio 1
> 
> The output I want is to have :
> ralph and 'elenour.. how can I do this?

You are doing the comparison the wrong way: you are saying:

for each line in the file:
    is the line in the dict?
    if no, print the line


What you want is:

for each key in the dict:
    is the key in the file?
    if no, print the key


It is not easy to try searching the file directly, so we copy the lines 
from the file into a set:

lines = set()
with open("data.tmp") as the_file:
    for line in the_file:
        line = line.strip().split("\t")[0]
        lines.add(line)


Here is a shorter way to do the same thing:

with open("data.tmp") as the_file:
    lines = set([line.strip().split("\t")[0] for line in the_file])


Now you can walk through the dict:

for name in diz:
    if name not in lines:
        print(name) 


Or, if you prefer:

names = set(diz)  # copy the keys from the dict into a set
print(names.difference(lines))


If you want to see the other way around:

print(lines.difference(names))




-- 
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to