python - Conditional merging in Python3 -


i trying merge variables keys existing in dictionary. here rules:

  1. if key exists, increment value counter one.
  2. if partial match key exists: a. if variable length smaller key re.search not none, increment value counter 1 b. if variable length larger key , re.search not none, replace key variable , increment counter one
  3. if variable exists after still has no match in dictionary, add variable dictionary

i have been able accomplish 1, 2a , 2b not sure how add 3. help/suggesstions appreciated. here script in present form: see "turtle" in dict.

animals = ["phant", "eleph", "tiger", "turtle", "zebra", "ostrich"] dict = {"horse":1, "elephant":1, "iger":1, "ostrich":1}  name in animals:      if name in dict:              dict[name]=dict[name]+1      else:              key, val in dict.items():                      if len(name) < len(key):                              m = re.search (name, key)                              if m != none:                                      print ("found match!", name)                                      dict[key] = dict[key] + 1                                      break                      elif len(name) > len(key):                               m = re.search (key, name)                               if m != none:                                      print ("found match!", name)                                      dict[name] = dict.pop(key) + 1                                      dict[name] = dict[name] + 1                                      break 

one way describe case #3 after looking @ code "if neither of break statements executed". can handle case putting else statement after for loop. code within block executed if for loop ran completion (or in other words, there no break statement run within loop):

animals = ["phant", "eleph", "tiger", "turtle", "zebra", "ostrich"] dict = {"horse":1, "elephant":1, "iger":1, "ostrich":1}  name in animals:     if name in dict:         dict[name]=dict[name]+1     else:         key, val in dict.items():             if len(name) < len(key):                 m = re.search (name, key)                 if m != none:                     print ("found match!", name)                     dict[key] = dict[key] + 1                     break             elif len(name) > len(key):                 m = re.search (key, name)                 if m != none:                     print ("found match!", name)                     dict[name] = dict.pop(key) + 1                     dict[name] = dict[name] + 1                     break         else:                 # line , 1 below new             dict[name] = 1 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -