Home > Back-end >  Get line number where in iteration an empty variable is encountered
Get line number where in iteration an empty variable is encountered

Time:08-26

first time asking a question, be gentle, please. I'm iterating over a dict that looks like this:

mydict = {
    'app_1': 'enabled',
    'app_2': 'enabled',
    'app_3': 'disabled',
    '': 'enabled',
}

...with this logic:

for key, value in mydict.items():
    if key:
        # ... is not empty, do something
    else:
        # ... app is empty, print error message about it

I'd like to get the line number where the empty key occurs. I've looked around on the net and I just can't figure it out. I'm really new to python and programming in general. Any pointers or advice would be highly appreciated.

  • Hi! Thanks for all the replies! I'm not looking for an index number but rather the line in the file where the empty key is. Is this possible? Thanks again!

CodePudding user response:

Dictionaries are in insertion order as of Python 3.6. So you can use something like this if the line number means order number of key, value pair.

mydict = {
    'app_1': 'enabled',
    'app_2': 'enabled',
    'app_3': 'disabled',
    '': 'enabled',
}
line_number = 1
for key, value in mydict.items():
    if key == "":
        print(line_number)
    line_number  = 1

CodePudding user response:

You can do something like this,

In [53]: for index, key_and_value in enumerate(mydict.items()):
    ...:     if not key_and_value[0]:
    ...:         print(index   1)

Updated to this,

In [53]: for index, key in enumerate(mydict):
    ...:     if not key:
    ...:         line_number = index   1
  • enumerate will give you the index while iterating.

  • Since you are only using key during iteration you don't need to use mydict.items

CodePudding user response:

Adding a little bit on to these other replies because you said you were new:

What you're looking for is usually called the "index" of a list. The thing is, dictionaries in python don't have indexes. Your dictionary items are still ordered, so if you create them in the way you did ('app1', 'app2'), etc., when you then put that dictionary in a for loop it will in fact iterate through each of them in order. The first one it looks at is the "app1" key, the second "app2", etc.

The way you would find out which ones aren't empty would be by creating a sort of index yourself. Have it increment by 1 each time it goes through the loop, and put some sort of condition (if key is not None, if key is None) that then prints that index.

Hope this helped a bit. This stuff can be confusing when you're starting out.

  • Related