Blackmagic42
Blackmagic42

Reputation: 83

Dictionary not returning correct value

Code below - followed by description of my problem;

ends_partial_dict = {
    'PLAIN END' : 'PE',
    'MPT' : 'MNPT',
    'PE': 'PE',}

original_description = (r'Pipe SA-106 GR. B SCH 40 PE 24" WALL smls'.upper())
item_split = original_description.split()

Returns: ['PIPE', 'SA-106', 'GR.', 'B', 'SCH', '40', 'PE', '24"', 'WALL', 'SMLS']

def item_end_partial() :
   not_found = True
   for key in ends_partial_dict:
        if key == item_split:
            item_end_partial_1 = ends_partial_dict[key]
            return (item_end_partial_1)
            not_found = False
            break
   if not_found :
            return ("What are ENDS?")
print(item_end_partial())

For some reason, it is returning my "if not_found" value of "What are ENDS?" instead of the dictionary value of 'PE'.

I've tried a number of different ways to adjust the dictionary value and the function setup but nothing has seemed to work. Anyone know why this is not pulling 'PE'?

Upvotes: 0

Views: 239

Answers (1)

quamrana
quamrana

Reputation: 39354

You have lots of redundancy in your code, plus you should be passing values into your function, not relying on global variables:

ends_partial_dict = {
    'PLAIN END' : 'PE',
    'MPT' : 'MNPT',
    'PE': 'PE',}

original_description = r'Pipe SA-106 GR. B SCH 40 PE 24" WALL smls'.upper()
item_split = original_description.split()
# Returns: ['PIPE', 'SA-106', 'GR.', 'B', 'SCH', '40', 'PE', '24"', 'WALL', 'SMLS']

def item_end_partial(item_split, ends_partial_dict) :
    for key in ends_partial_dict:
        if key in item_split:
            return ends_partial_dict[key]
    return "What are ENDS?"

print(item_end_partial(item_split, ends_partial_dict))

Upvotes: 1

Related Questions