I’m trying to see if the first two or three numbers in the “code” variable is in the dictionary, and if it is found it returns the key for that number

   code=("569010002151") 
    countrycode = {
        "Norway": 70,
        "Denmark": 57,
        "Sweden": 73,
        "Finland": 64,
        "Iceland": 569
        }
    
    value = (int(code[0:2]) or int(code[0:3])) 
    
    def country(code):
        for k,v in countrycode.items():
            if v == value:
                print("The code is from", k)
                break
            else:
                print("Code not valid")
              
    (country(code))  

The preferred output with this “code” string would be The code is from Iceland

I have found that if I remove “or int(code[0:3])” the code seems to work somewhat, but then the Iceland countrycode does not work.

Any help would be greatly appreciated.

Answer

I’m assuming this is Python?

The first thing to improve is to define the country codes as strings instead of ints. Strings are used when comparing patterns vs its which Are used for math operations. That will look like:

  countrycode = {
      "Norway": “70”,
      "Denmark": “57”,
      "Sweden": “73”,
      "Finland": “64”,
      "Iceland": “569”
 }

Next, you don’t really need ‘value’. And it’s note going to work the way you expect anyways. The reason it works of you remove the statement after ‘or’ is because ‘or’ is actually a logical operator. It actually will evaluate to ‘True’ or ‘False’.

Next, you can probably remove the function declaration in this case since it’s only used once and it’s being called immediately after. The loop looks ok but instead of comparing equality to value, use the ‘in’ operator. This checks that a string is contained in another. The entire script will look like this:

 code=("569010002151") 
 countrycode = {
      "Norway": “70”,
      "Denmark": “57”,
      "Sweden": “73”,
      "Finland": “64”,
      "Iceland": “569”
   }

    for k,v in countrycode.items():
        if v in code[0:3]
            print("The code is from", k)
            break
        else:
            print("Code not valid")

Sorry for the formatting. I’m on mobile…