Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the dict as below, if same value is found more than once then my dict key must be created with incremental numbering.

TT = {

                "TYPE_1" : ['ERROR'],

                "TYPE_2": ['FATAL'],

                "TYPE_3" : ["TIME_OUT"],

                "TYPE_4" : ['SYNTAX'],

                "TYPE_5" : ['COMPILE'],

        

  }

  m1 = "ERROR the input is not proper"

  m2 = "This should have not occured FATAL"

  m3 = "Sorry TIME_OUT"

  m4 = "SYNTAX not proper"

  m5 = "u r late its TIME_OUT"

The value "TIME_OUT" occur twice in the search.

  count = 0

  for key in TT.keys():

    print(key)

    Key_1 = key

    

    while key_1 in TT:

      count = count+1

      key_1 = key + "_{}".format(count)

The above code gives error Key_1 not defined.

Expected OUTPUT:

if same value is occuring more than once then the dict key should be created with incremental numbering "TYPE_3_1" : ["TIME_OUT"],

 TT = {

               "TYPE_1" : ['ERROR'],

               "TYPE_2": ['FATAL'],

               "TYPE_3" : ["TIME_OUT"],

               "TYPE_3_1" : ["TIME_OUT"],

               "TYPE_4" : ['SYNTAX'],

               "TYPE_5" : ['COMPILE'],

       

 }

1 Answer

0 votes
by (36.8k points)

There can be an efficient way of solving this if you can rethink some of a data structure but if that is not an option you may be able to try this.

inputs = ["ERROR the input is not proper", 

"This should have not occurred FATAL",

"Sorry TIME_OUT",

"SYNTAX not proper",

"u r late its TIME_OUT"]

basic_types = {

                "TYPE_1" : ['ERROR'],

                "TYPE_2": ['FATAL'],

                "TYPE_3"  : ["TIME_OUT"],

                "TYPE_4" : ['SYNTAX'],

                "TYPE_5" : ['COMPILE'],

        }

type_counts = {}

results = {}

for sentence in inputs:

    for basic_type in basic_types:

        if basic_types.get(basic_type)[0] in sentence:

            type_counts[basic_type] = type_counts.get(basic_type, 0) + 1

            

            if type_counts[basic_type] == 1:

                results[basic_type] = [basic_types.get(basic_type)[0]]

            else:

                results[basic_type+"_{}".format(type_counts[basic_type] - 1)] = [basic_types.get(basic_type)[0]]

print(results)

 Improve your knowledge in data science from scratch using Data science online courses

Browse Categories

...