0
#sample input 
dict_ = {'country': {'0': 'a,b,c','1': 'xyz'}}

country_name = []
for country in dict_['country'].values():
    if ',' in country:
        country_name.append(country.split(','))
    else:
       country_name.append([country])
#op of above code
[['a', 'b', 'c'], ['xyz']] 

how to write above code using list comprehension, so far i have tried the below. .I need to add else condition in these list comprehension

[x.split(',') for x in dict_['country'].values() if ',' in x] 

expected output using list comprehension

[['a', 'b', 'c'], ['xyz']]
qaiser
  • 2,770
  • 2
  • 17
  • 29
  • Does this answer your question? [if/else in a list comprehension?](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension) – vb_rises Dec 23 '19 at 15:29

1 Answers1

4

Your problem is that the values that do not contain a comma are unused, so you need an else

[x.split(',') if ',' in x else [x] for x in dict_['country'].values()]

But specific case here : using str.split always returns a list.If the delimiter is not present in the original text, you'll just get an list with 1 element,

>>> "a,b,c".split(',')
['a', 'b', 'c']
>>> "abc".split(',')
['abc']
>>> "a,b,c".split(',', 1) # maxsplit param
['a', 'b,c']

You can use that to remove the condition

[x.split(',') for x in dict_['country'].values()]

Your original code is just :

country_name = []
for country in dict_['country'].values():
    country_name.append(country.split(','))
azro
  • 53,056
  • 7
  • 34
  • 70