In python, how do I call upon excel sheet column to match a user input?

Question:

import pylightxl as xl

with open('city.xlsx', 'rb') as f:
    db = xl.readxl(f)

l = list(db.ws(ws='Sheet1').col(col=3))

cc = input("What is your country code?:  ").upper()

d ={}
for cc in l:
    CC = cc.upper()
    if CC in d:
        d[CC] = d[CC] + 1
    else:
        d[CC] = 1


l2 = list(db.ws(ws='Sheet1').col(col=3)[0:])
matches = 0
for cc in l2:
    if cc == #This is where I want to match the 3 letter Code to Excel
        matches += 1
print("{} Countries match".format(matches)) 

I am currently trying to get the cc = input (max 3 letters) to count any of the matching country codes from the city.xlsx. If I were to input for example AFG into the

if cc = "AFG":

when I run the script I would enter AFG and get a count of the matching country codes, however that only works for the one specific country code, I am wondering how I can make it so that the script can apply to any and all the codes that are within the xlsx file. (The excel file is from the World Database converted to excel)

enter image description here

Asked By: Etropal

||

Answers:

You can count the occurences of a value in a list by using the function count(x) from python built-in module collections.

import pylightxl as xl
import collections

with open('city.xlsx', 'rb') as f:
    db = xl.readxl(f)

l = db.ws(ws='Sheet1').col(col=3)

cc = input("What is your country code?:  ").upper()

matches = l.count(cc)

print("{} Countries match".format(matches)) 

# Output :

What is your country code?:   afg
4 Countries match

Note : You don’t need to add list() to db.ws(ws='Sheet1').col(col=3) since this one is a list (see here).

Answered By: abokey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.