I am trying to compare a list of words to a dictionary to see if there are any matches. How do I do this, as diction.has_key() does not work for lists?

Recommended Answers

All 2 Replies

One way ...

d = {'Jim': 19, 'Slim': 45, 'Peter': 23, 'Joe': 30, 'Mark': 27}
q = ['Frank', 'Hank', 'Joe', 'Luke', 'Paul']
for key in d.keys():
    if key in q:
        print key

If there are a lot of words to look up, use sets. They are indexed and are much faster than a list.
reference_list=[ "AA", "AB", "BB", "AC", "BC" ]
ref_set=set(reference_list)
lookup_set=set(["AB", "BB", "CC"])
print lookup_set.intersection(ref_set)
print lookup_set.difference(ref_set)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.