Dictionary item not returning correct value

Question:

I’m creating a function that returns a proper field name based on a number that is input. The test script is just returning the first key, not the desired value (1).

def GetFieldName(bldgcode):
    bldgcode = {1: "SFCount", 2: "MFCount", 3: "ComCount", 4: "IndCount", 5: "CityCount", 6: "ShedCount", 7: "SchCount", 8: "ChurCount"}
    for values in bldgcode:
        return values
#test for get field name
print(GetFieldName(8))

Running the script is giving me 1 when it should be ChurCount

Asked By: PieCharmer

||

Answers:

If you print the loop part,

for values in bldgcode:
    print(values)

You’d notice that you are looping through the keys of the dict. And the return statement stops after returning the first value it finds, which is 1. Also, you’re overwriting the bldgcode=8 argument the next line when you’re declaring the dict. So, you need to use a different variable for the parameter and add a condition to check if a key in the dict is equal to the input argument.

def GetFieldName(i):
    bldgcode = {1: "SFCount", 2: "MFCount", 3: "ComCount", 4: "IndCount", 5: "CityCount", 6: "ShedCount", 7: "SchCount", 8: "ChurCount"}

    for k,v in bldgcode.items():
        if k==i:
            return v

print(GetFieldName(8))
Answered By: Ash Nazg

How about directly use dict[key] to get name?

def GetFieldName(bldgcode):
    code2name = {1: "SFCount", 2: "MFCount", 3: "ComCount", 4: "IndCount", 5: "CityCount", 6: "ShedCount", 7: "SchCount", 8: "ChurCount"}
    return code2name[bldgcode]
#test for get field name
print(GetFieldName(8))
Answered By: Sinon
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.