简体   繁体   中英

if there is not key and value pair in list then skip this data using python

I have list of data that contains the key and values data but some time it contains only data. I want to skip this type of data.

I got the below error:-

Example :-

formatted_desc_split = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

for each_split_data in formatted_desc_split:
    split_by_colon = each_split_data.split(":")
Error :-
IndexError: list index out of range

I want to skip Akshay Godase is from pune data. if there is not key and value pair in list then i want to skip this data. I am not able to split this data because in first index there is not key values paire.

How can i solve the above proble?

Use the following instead:

formatted_desc_split = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

for each_split_data in formatted_desc_split:
    if ":" not in each_split_data:
        ...

May not be an elegant way, but the following code does what you wanted. Just for the sake of an alternative solution.

formatted_desc_split = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

my_dict = {}

for each_split_data in formatted_desc_split:
    split_by_colon = each_split_data.split(":")
    if len(split_by_colon) == 2:
        my_dict[split_by_colon[0]] = split_by_colon[1]
    print(my_dict)

Use list comprehensions. Concise, readable, pythonic:

>>> strings = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']
>>> [s for s in strings if ':' in s]
['Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM