Dictionary key and string comparison in python

I compared the dictionary key with a predefined string, eventhough it looks similar, but the comparison always fails. for example: key='eng-101' and 'eng-101' string are not same.

please help

for key, value in course_dict.items() :
        print('search ky is --'+key)
        print('the elective courses are---',courses)

        #finding the key in string
        if(courses.find(key)==-1):
            print('key not found--'+key)

        else:
            print('---------------------the key found is---'+key)
            key=str(key +'-101,')
            key=key.replace(' ','')
            first_year_el_course+=key

            print(elective_counter)
            print(first_year_el_course)
            print('newly formatter key--:   '+key)

            print(key=='eng-101')   

Upvotes: 0

Views: 71

Answers (2)

wgb22
wgb22

Reputation: 247

@DipenDadhaniya is correct but it is always better to use string formatting. This should make your code more concise and easy to read.

Be careful about changing the iteration variable key during an iteration as this can sometimes lead to unintended consequences which can be difficult to debug. Give it a new name such as new_key.

new_key = '{}-101'.format(key.replace(' ', ''))

Upvotes: 1

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

Change:

key=str(key +'-101,')    # Remove the comma at the end, otherwise key will be 'eng-101,' and not 'eng-101'.

To:

key = str(key) + '-101'  # Convert key to string. '-101' is already a string.

Upvotes: 1

Related Questions